如何根据来自多个降价文件的数据编写JSON文件

时间:2019-06-14 08:41:34

标签: javascript node.js json gulp markdown

我需要使用Markdown文件中的数据构建API。

我大约有100个markdown文件,文件顶部的数据如下:

---
title: Lorem ipsum
category: component
primaryKeywords: curved horizon
secondaryKeywords: css block content seperator
---

所需的输出是一个.json文件,其中.md文件中的所有数据都作为数组中的对象。

示例:

[
  {
    "title": "Lorem ipsum",
    "category": "component",
    "primaryKeywords": "curved horizon",
    "secondaryKeywords": "css block content seperator"
  },
  {
    "title": "Lorem ipsum",
    "category": "component",
    "primaryKeywords": "curved horizon",
    "secondaryKeywords": "css block content seperator"
  },
  {
    "title": "Lorem ipsum",
    "category": "component",
    "primaryKeywords": "curved horizon",
    "secondaryKeywords": "css block content seperator"
  }
]

JSON文件应作为前端构建的一部分生成。我正在用口水。

我试图做这样的事情:

gulp.task('search-api', function (cb) {
  const fs = require('fs');
  const matter = require('gray-matter');
  const str = fs.readFileSync('./src/docs/01-Components/02-Layout/03-bow.md', 'utf8');
  console.log(matter(str));
});

我能够在控制台中显示来自1个文件的数据。但是我需要帮助来显示./src/docs/中所有文件的数据,然后将其合并为1个结果并将其解析为1个JSON文件。

我该怎么做?感谢所有帮助和建议。

2 个答案:

答案 0 :(得分:1)

基本上你想做的是

  1. 创建writeStream
  2. 添加“ [”
  3. 添加对象

  4. 每个文件的
  5. 循环:添加逗号“,”

  6. 添加另一个对象
    :loopend
  7. 添加另一个结尾“]”

为此,您可以使用walk软件包。

const fs = require('fs');
const walk = require('walk');
const matter = require('gray-matter');
const dirname = "./src/docs";
const path = require('path');
const walker = walk.walk(dirname);
let prefix = ""
const stream = fs.createWriteStream("json.json", {flags:'a'});
stream.write("[\n");
walker.on("file",  (root, fileStats, next) => {
    const str = fs.readFileSync(path.join(root, fileStats.name), 'utf8');
    stream.write(prefix);
    stream.write(JSON.stringify(matter(str),null, 4));
    prefix=","
    next();
});

walker.on("errors", function (root, nodeStatsArray, next) {
    next();
});

walker.on("end", function () {
    stream.write("\n]");
    stream.end();
});

PS:我从头开始编写了这段代码,以给您一些提示。如有错误,请随时进行编辑。

答案 1 :(得分:1)

这是我使用节点而不是吞咽进行的“锻炼”:

const fs = require('fs');
const glob = require('glob');
const os = require('os');

const markdownFiles = glob.sync("./markdown/*.md");  // an array of files in the 'markdown' directory
let finalArray = [];


function buildJSONfile() {

  let contents;

  markdownFiles.forEach((nextFile) => {

    contents = fs.readFileSync(nextFile, "UTF8");

        // os.EOL = \r\n for windows, \n for POSIX
    let grayMatter = contents.match(new RegExp(`---${os.EOL}((.*${os.EOL})*?)---`));  // get just the content between the "---"s in array[1]

    //  add quotes around all the keys and values and add commas between key:value pairs
    let addedQuotes = grayMatter[1].replace(/^([^:]*)(:\s*)(.*)(\s*)/mg, '"$1"$2"$3",');  

    addedQuotes = addedQuotes.slice(0, addedQuotes.length - 1);  // remove the extra comma at the end of the last value

    let addedBrackets = `{${addedQuotes}}`;  // add brackets around the whole thing so that we can use JSON.parse

    let JSONobject = JSON.parse(addedBrackets);

    finalArray.push(JSONobject);
  });

      // write to a file : result.json
  fs.writeFileSync("./result.json", JSON.stringify(finalArray, null, '\t'), "UTF8");
};

buildJSONfile();  // comment out if using gulp

运行node yourFileNameHere.js
您也可以将其放入gulpfile.js,然后通过gulp buildJSONfile运行它。