Categories
JavaScript Answers Nodejs

How to add to an existing JSON file in Node.js?

Spread the love

Sometimes, we want to add to an existing JSON file in Node.js.

In this article, we’ll look at how to add to an existing JSON file in Node.js.

How to add to an existing JSON file in Node.js?

To add to an existing JSON file in Node.js, we can use the fs.readFile method.

For instance, we have:

["foo","bar"]

in results.json

Then we write:

const { promises: fs } = require("fs");
const currentSearchResult = 'example'

const write = async () => {
  const data = await fs.readFile('results.json')
  const json = JSON.parse(data)
  json.push(currentSearchResult)
  await fs.writeFile("results.json", JSON.stringify(json))
}
write()

to call fs.readFile to read results.json into data.

Then we call JSON.parse with data to parse data into an onject.

Then we call json.push with currentSearchResult to add currentSearchResult to json assuming json is an array.

Finally, we call fs.writeFile with the file path and the content to write to the file.

Now result.json has:

["foo","bar","example"]

Conclusion

To add to an existing JSON file in Node.js, we can use the fs.readFile method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *