How to write a JSON object to a file in Node.js

Explore how to save a JSON object to a file in Node.js and retrieve it later

Sometimes, the best way to store some data in a Node.js application is to save it to the file system.

If you have an object that can be serialized toJSON format,you can use itJSON.stringify()Methods andfsmethodfs.writeFileSync()It synchronously writes a piece of data to the file:

const fs = require('fs')

const storeData = (data, path) => { try { fs.writeFileSync(path, JSON.stringify(data)) } catch (err) { console.error(err) } }

To retrieve data, you can usefs.readFileSync():

const loadData = (path) => {
  try {
    return fs.readFileSync(path, 'utf8')
  } catch (err) {
    return false

We use a synchronous API, so once we get the data, we can easily return the data.

We can also decide to use the asynchronous version,fs.writeFilewithfs.readFile, Although the code will change, I suggest you read the followingHow to use Node.js to write fileswithHow to read files using Node.jsfor this.

Download mine for freeNode.js manual

More node tutorials: