简体   繁体   中英

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. When calling that function with another json object, I want to append that object to the file.

Currently I am using jsonfile for that.

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.

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:

{"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. Also that needs to work when the file is empty.

Use appendFile() instead of writeFile(). writeFile() is to write a new file or overwrite existing file if any. While appendFile() is to append Content to the existing file if any or create a new file and add the content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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