How do I add to an existing json file in node.js

If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.

var fs = require('fs')

var currentSearchResult="example"

fs.readFile('results.json', function (err, data) {
    var json = JSON.parse(data)
    json.push('search result: ' + currentSearchResult)

    fs.writeFile("results.json", JSON.stringify(json))
})

Leave a Comment