Search code examples
javascriptnode.jsjsonbody-parserwritefile

How to append data to a JSON with a specific index in javascript/nodejs


I'm doing a basic 'Visitor Book' function.
Users can submit a little form (with three inputs : name, msg and emoji).
I grab it with req.body in my router component. I'm using nodejs, with express and bodyparser.

I only want to store this data in a JSON, don't want any database involved here. I'm in trouble with the writeFile method, using 'fs' module. It work but it push the new data outside the single-array of my JSON file.

Do you know if I can push in inside the array ? Like a .push method, but with writeFile/appendFile/wathever that works good with json files. Here is my code :

app.post (router) :

app.post('/visitorBook', async (req, res) => { 
    let formData = {
        name: req.body.name,
        msg: req.body.msg,
        emoji: req.body.emoji
    }
    try {
        console.log(req.body)
        let data = JSON.stringify(formData, null, 2);

        fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file
            flag:'a' // this flag specify 'please append it' over 'please override file'
        }
        }, (err) => {
            console.log('error :', err)
        });


        res.redirect('/contact') 
    } catch (error) {
        console.error('/visitorBook route error : ', error)
    }
})

My JSON :

[
    {
        "name": "test1",
        "msg": "test1",
        "emoji": "<i class='fas fa-hippo fa-3x'></i>"
    },
    {
        "name": "test2",
        "msg": "test2",
        "emoji": "<i class='fas fa-hippo fa-3x'></i>"
    }
]


{
  "name": "sd",
  "msg": "sd",
  "emoji": "<i class='fas fa-kiwi-bird fa-3x'></i>"
}

So the last one with "sd" in name and msg is the pushed one. The 2 other are manually written by me, for readFile tests.

I hope I provided all the information needed. Not used to post here... Thanks you.


Solution

  • If you read from the existing file and parse it with JSON.parse, you will be able to actually use Array.push on it. And then you can write the stringified result back into the file:

    fs.readFile("./views/scripts/dataVisitorBook.json", function (err, data) {
      if (err) throw err;
      let data = JSON.parse(data.toString('utf8'));
    
      data = JSON.stringify(data, null, 2);
    
      fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file
          flag:'a' // this flag specify 'please append it' over 'please override file'
      }
      }, (err) => {
          console.log('error :', err)
      });
    })
    

    It might not be optimal though as it is likely to take more time as the file grows bigger.