Search code examples
node.jsjsonexpressfilesystemsfs

How to append a file using fs.appendFile() but not write another JSON object


I'm trying to write a key-value pair in my json file using fs.appendFile().

Here's my code:

 router.post('/add', function(req, res) {
  var article = {
    title: req.body.title,
    content: req.body.content
  }

  var articleData = {};

  articleData[article.title] = article.content;

  var textData = JSON.stringify(articleData, null, 2);

  fs.appendFile('model/text.json', textData, 'utf8', finished);

  function finished () {
    console.log('Finished writing');
  }
});

But in my text.json file, I'm only getting this:

{
  "test1": "test1"
}{
  "test2": "test2"
}

I cannot manage to append it like this:

{
    "test1": "test1",
    "test2": "test2"
}

Solution

  • First you need to read your file and then process json data to add your content into it. And your second step will be write file. You can refer following example.

    fs.readFile('model/text.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        objData = JSON.parse(data); //now it an object
        objData.test2 = 'test2'; //add/append desired data
        jsonData = JSON.stringify(objData); //convert it back to json
        fs.writeFile('model/text.json', jsonData, 'utf8', callback); // write it back 
    }});