Javascript 如何基于多个标记文件中的数据编写JSON文件
我需要用降价文件中的数据构建一个API 我有大约100个降价文件,文件顶部有如下数据:Javascript 如何基于多个标记文件中的数据编写JSON文件,javascript,node.js,json,gulp,markdown,Javascript,Node.js,Json,Gulp,Markdown,我需要用降价文件中的数据构建一个API 我有大约100个降价文件,文件顶部有如下数据: --- title: Lorem ipsum category: component primaryKeywords: curved horizon secondaryKeywords: css block content seperator --- 所需的输出是一个.json文件,其中.md文件中的所有数据都作为数组中的对象 例如: [ { "title": "Lorem ipsum",
---
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/
中所有文件的数据,然后将其合并为一个结果并将其解析为一个JSON文件
我该怎么做?感谢所有的帮助和建议。基本上你想做的是
:loopend
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:这段代码是我从头开始写的,目的是给你一些提示。如果有bug,请随意编辑。基本上你想做的是
:loopend
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:这段代码是我从头开始写的,目的是给你一些提示。如果有bug,请随意编辑。我这样做是为了“练习”使用node,而不是吞咽:
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
使用节点yourFileNameHere.js运行
您还可以将其放入一个gulpfile.js中,并通过gulpbuildjsonfile
运行它。我使用node而不是gulp执行此操作作为“练习”:
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
使用节点yourFileNameHere.js运行
您还可以将其放入gulpfile.js中,并通过gulpbuildjsonfile
运行它,谢谢!我知道你在做什么。您的示例不起作用,我得到:错误:enoint:没有这样的文件或目录,请打开“03 bow.md”
,但我会看看是否能找到解决方案。无论如何,这些步骤都很好,我喜欢这种方法。为此,您需要path.join
文件名。编辑了答案@BenderBoii随意编辑path.join(console.log path.join的内容以确认)仍然无法使此示例正常工作。一些标记文件位于子文件夹中,这就是它引发错误的原因<代码>fs.js:115抛出错误;^错误:eNote:没有这样的文件或目录,请打开“src\docs\02 Installation and Usage.md”
该文件位于名为03 code Guidelines
的子文件夹中,因此该文件的正确路径是src\docs\03 code Guidelines\02 Installation and Usage.md
有关如何解决此问题的任何建议?编辑了答案,使用root
变量。它包含文件夹路径。再次通过控制台记录路径来测试它谢谢!通过删除dirname
并仅使用root
使其工作。谢谢!我知道你在做什么。您的示例不起作用,我得到:错误:enoint:没有这样的文件或目录,请打开“03 bow.md”
,但我会看看是否能找到解决方案。无论如何,这些步骤都很好,我喜欢这种方法。为此,您需要path.join
文件名。编辑了答案@BenderBoii随意编辑path.join(console.log path.join的内容以确认)仍然无法使此示例正常工作。一些标记文件位于子文件夹中,这就是它引发错误的原因<代码>fs.js:115抛出错误;^错误:eNote:没有这样的文件或目录,请打开“src\docs\02 Installation and Usage.md”
该文件位于名为03 code Guidelines
的子文件夹中,因此该文件的正确路径是src\docs\03 code Guidelines\02 Installation and Usage.md
有关如何解决此问题的任何建议?编辑了答案,使用root
变量。它包含文件夹路径。再次通过控制台记录路径来测试它谢谢!通过删除dirname
并仅使用root
使其工作。非常酷。谢谢但是我不能去上班。我得到:[10:50:46]类型错误:无法在Gulp.Gulp.task(D:\dna\gulpfile.js:555:33)的Array.forEach()中读取markdownFiles.forEach(D:\dna\gulpfile.js:548:17)的null属性“1”
有什么想法吗?我在glob.sync
语句中为标记文件使用了一个名为markdown
的文件夹。将其更改为标记文件的路径。@标记我正在使用nuxt。可以将您的代码用于webpack?非常酷。谢谢但是我不能去上班。我得到:[10:50:46]类型错误:无法在Gulp.Gulp.task(D:\dna\gulpfile.js:555:33)的Array.forEach()中读取markdownFiles.forEach(D:\dna\gulpfile.js:548:17)的null属性“1”
有什么想法吗?我在glob.sync
语句中为标记文件使用了一个名为markdown
的文件夹。将其更改为标记文件的路径。@标记我正在使用nuxt。是否可以将您的代码与Web包一起使用?