(变量文件包含 URL .json 文件数组)。子目录中的一个文件包含:
[ {"name": "John"} ]
然后我得到通用文件 get.json,其中包含结构中子目录中的所有文件(是的,我知道这不是有效的 JSON):
[ {"name": "John"} ]
[ {"name": "Sergei"} ]
我想以这种结构获取此文件:
[ {name: "John"}, {name: "Sergei"} ]
我的代码
recursive(`${dirPath}`, ['delete.json', 'put.json'], function (err, file) {
const write = fs.createWriteStream(`${dirPath}/get.json`);
file.forEach(item => {
fs.createReadStream(item).pipe(write);
})
write.on('finish', () => {
fs.createReadStream(`${dirPath}/get.json`).pipe(res);
})
});
最佳答案
我生命中的一天就完成了这项任务!
recursive(`${dirPath}`, ['delete.json', 'put.json'], function (err, file) {
const write = fs.createWriteStream(`${dirPath}/get.json`);
const usersArr = [];
let readStream;
file.forEach(item => {
readStream = fs.createReadStream(item);
readStream.on("data", (data) => {
JSON.parse(data).map(item => usersArr.push(item));
});
})
readStream.on("end", (data) => {
write.write(JSON.stringify(usersArr, null, " "), () => {
console.log('Completed');
});
fs.createReadStream(`${dirPath}/get.json`).pipe(res)
});
});
关于javascript - 如何将多个数组的结构更改为数组对象 Node.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51614690/