使用nodejs在文件中将JSON对象添加到JSON Array
我在2个不同的文件中有2个用户列表。我想要实现的是创建一个.json文件,其中来自2个不同文件的所有这些用户都是json文件中json对象的形式。
EX:
file1 : ["[email protected]", "[email protected]"]
file2 : ["[email protected]", "[email protected]"]
最终的Json文件:
[
{
"email" : "[email protected]"
},
{
"email" : "[email protected]"
}
.....
]
我是节点js的新手,有人可以帮忙这样做。
到目前为止我用JSON文件编写的内容:
function createJSONAndWrite(email){
var arrayList = Object();
arrayList.email = email;
jsonfile.readFile(file, function(err, obj) {
obj.push(arrayList);
jsonfile.writeFileSync(file, obj);
});
}
这不起作用
请帮我
提前致谢!!
回答如下:这是一个全新的解决方案:
const fs = require('fs-extra');
async function generateOutputFile() {
const arrayOne = await fs.readJson(fileOne);
const arrayTwo = await fs.readJson(fileTwo);
const output = arrayOne.concat(arrayTwo).map(email => {email});
await fs.writeJson(outputFile, output);
}
请注意,我使用的是fs-extra
而不是jsonfile
,因为它通过提供Promise支持(需要Node.js 8)来大大简化了代码。
我的代码......
- 异步读取文件和waits for that to finish
- concatenates both arrays into one array
- 使用
"[email protected]"
将数组项(email
)转换为具有map
属性的对象 - 异步将输出写入文件