简体   繁体   English

使用nodejs将json对象附加到文件

[英]append json objects to file with nodejs

I simply want to write a json object into a file (not necessarily a .json file) after calling a certain function. 我只是想在调用某个函数后将json对象写入文件(不一定是.json文件)。 When calling that function with another json object, I want to append that object to the file. 当使用另一个json对象调用该函数时,我想将该对象附加到文件中。

Currently I am using jsonfile for that. 目前,我正在使用jsonfile

var jsonfile = require('jsonfile');
...
users_file = "./users_file";
function update(user_json) {
    jsonfile.writeFile(users_file,user_json), function(err) {
        console.error(err);
    });
}

But calling update again with another json object, the first line will be overwritten. 但是使用另一个json对象再次调用update时,第一行将被覆盖。

example: 例:

json1 = {"id":123456,"first_name":"John","last_name":"Smith","username":"johnsmith"}
json2 = {"id":654321,"first_name":"marc","last_name":"cold","username":"marccold"}

when calling update(json1) and later update(json2) I want the file to look like this: 当调用update(json1)和更高版本的update(json2)我希望文件看起来像这样:

{"id":123456,"first_name":"John","last_name":"Smith","username":"johnsmith"}
{"id":654321,"first_name":"marc","last_name":"cold","username":"marccold"}

Currently the second line is replacing the first line. 当前第二行正在替换第一行。 I tried to read the file first and then concat both json objects but that failed. 我尝试先读取文件,然后再连接两个json对象,但是失败了。 Also that needs to work when the file is empty. 当文件为空时,这也需要工作。

Use appendFile() instead of writeFile(). 使用appendFile()而不是writeFile()。 writeFile() is to write a new file or overwrite existing file if any. writeFile()用于写入新文件或覆盖现有文件(如果有)。 While appendFile() is to append Content to the existing file if any or create a new file and add the content. 而appendFile()用于将Content附加到现有文件(如果有)或创建新文件并添加内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM