quotes-nextjs

My favourite quotes. (nextjs)
git clone http://git.hanabi.in/repos/quotes-nextjs.git
Log | Files | Refs | LICENSE

generateRandom.js (2008B)


      1 const { readdir, readFile } = require("fs/promises");
      2 const { join } = require("path");
      3 const { createWriteStream } = require("fs");
      4 
      5 async function main() {
      6   try {
      7     const quotesANDauthors = [];
      8     const authors = await readdir("quotes");
      9     for (const author of authors) {
     10       const allFiles = await readdir(join("quotes", author));
     11       const { details, quotes } = getDetailsANDQuotes(allFiles);
     12 
     13       if (!details) throw new Error(`Error finding details`);
     14       if (quotes.length < 1) throw new Error(`Not enough quotes`);
     15 
     16       for (const quote of quotes) {
     17         const { data } = await readFrontMatter(author, quote);
     18 
     19         const { draft } = data;
     20         if (draft) continue;
     21 
     22         const quoteObj = createQuoteObj(author, data, quote);
     23         quotesANDauthors.push(quoteObj);
     24       }
     25     }
     26 
     27     const writeStream = createWriteStream("./random-quotes.js");
     28     writeStream.write(`module.exports = [`);
     29     for (const obj of quotesANDauthors) writeStream.write(JSON.stringify(obj) + ",");
     30     writeStream.write("]");
     31   } catch (err) {
     32     errHandler(err);
     33   }
     34 }
     35 
     36 main();
     37 
     38 const errHandler = (err) => {
     39   console.error(err);
     40 };
     41 
     42 async function readFrontMatter(author, quote) {
     43   const matter = require("gray-matter");
     44 
     45   try {
     46     const fileBuffer = await readFile(join("quotes", author, quote));
     47     const fileStr = fileBuffer.toString();
     48     const frontMatter = matter(fileStr);
     49     return frontMatter;
     50   } catch (err) {
     51     errHandler(err);
     52   }
     53 }
     54 
     55 function makeUri(quote) {
     56   return quote.replace(/\.md$/, "");
     57 }
     58 
     59 function getDetailsANDQuotes(allFiles) {
     60   const details = allFiles.filter((_) => _ == "data.md")[0];
     61   const quotes = allFiles.filter((_) => _ != "data.md");
     62   return { details, quotes };
     63 }
     64 
     65 function createQuoteObj(author, data, quote) {
     66   const { attributed, date, misattributed, tags, title, unverified } = data;
     67   const uri = makeUri(quote);
     68   return {
     69     attributed,
     70     author,
     71     date,
     72     misattributed,
     73     tags,
     74     title,
     75     unverified,
     76     uri,
     77   };
     78 }