0

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.

2
  • 2
    try using the function appendFile() instead of writeFile() Commented Jul 13, 2015 at 11:49
  • thanks. You can add this as an answer, if you want. Commented Jul 15, 2015 at 3:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.