我想合併nodejs目錄中的所有json文件。這些文件正在被用戶和所有我上傳]我知道他們的名字是設備「計數」.json。每次增加計數。我知道json-concat,但我如何使用它來合併目錄中的所有文件?合併目錄中的所有json文件nodejs
jsonConcat({
src: [],
dest: "./result.json"
}, function (json) {
console.log(json);
});
我想合併nodejs目錄中的所有json文件。這些文件正在被用戶和所有我上傳]我知道他們的名字是設備「計數」.json。每次增加計數。我知道json-concat,但我如何使用它來合併目錄中的所有文件?合併目錄中的所有json文件nodejs
jsonConcat({
src: [],
dest: "./result.json"
}, function (json) {
console.log(json);
});
如果你讀docs仔細您會看到這部分:
對象傳遞的選項可能包含以下鍵值:
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文件移動到某個具體路徑。
2)檢查這個代碼:
jsonConcat({
src: './path/to/json/files',
dest: "./result.json"
}, function (json) {
console.log(json);
});
和here is the prove how it uses src param
主要是它的開發者不僅需要使用3擋部件包,還深入到它的來源。
簡而言之: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);
});