合并目录nodejs中的所有json文件
我想合并nodejs中的一个目录中的所有json文件。 这些文件正在被用户上传和我所知道的是他们的名字是设备“计数”.json。 每增加一次计数。 我知道json-concat,但我如何使用它来合并目录中的所有文件?
jsonConcat({ src: [], dest: "./result.json" }, function (json) { console.log(json); });
如果你仔细阅读文档你会看到这个部分:
传递的选项对象可能有以下键:
src: (String) path pointing to a directory (Array) array of paths pointing to files and/or directories defaults to . (current working directory) Note: if this is a path points to a single file, nothing will be done.
所以这里是修复:
1)移动json文件到一些具体的path。
2)检查这个代码:
jsonConcat({ src: './path/to/json/files', dest: "./result.json" }, function (json) { console.log(json); });
这里是certificate它如何使用src参数
大多数情况下,开发人员不仅需要使用第三方软件包,还需要深入研究它的来源。
简而言之:KISS(:
您可以使用fs
模块读取目录中的文件,然后将它们传递给json-concat
。
const jsonConcat = require('json-concat'); const fs = require('fs'); // an array of filenames to concat const files = []; const theDirectory = __dirname; // or whatever directory you want to read fs.readdirSync(theDirectory).forEach((file) => { // you may want to filter these by extension, etc. to make sure they are JSON files files.push(file); } // pass the "files" to json concat jsonConcat({ src: files, dest: "./result.json" }, function (json) { console.log(json); });