Sometimes you want to store a JSON object to a file in a Node.js application and then retrieve it later. For example, when you are creating a new RESTful API, storing data on the local file system can be a good choice. You can skip the database setup and save JSON data to a file.

In this article, you'll learn how to write a JSON object to file in Node.js. In my previous article, we looked at how to read and write files in Node.js. If you need more information about reading and writing files, take a look at it.

Write JSON to File

JavaScript provides a built-in JSON object for parsing and serializing JSON data. You can use the JSON.stringify() method to convert your JSON object into its string representation, and then use the file system fs module to write it to a file.

Here is an example that uses the fs.writeFile() method to asynchronously write a JSON object to a file:

const fs = require('fs')

// create a JSON object
const user = {
  id: 1,
  name: 'John Doe',
  age: 22
}

// convert JSON object to a string
const data = JSON.stringify(user)

// write JSON string to a file
fs.writeFile('user.json', data, err => {
  if (err) {
    throw err
  }
  console.log('JSON data is saved.')
})

To pretty-print the JSON object to the file, you can pass extra parameters to JSON.stringify():

// pretty-print JSON object to string
const data = JSON.stringify(user, null, 4)

The fs module also provides a method called writeFileSync() to write data to a file synchronously:

try {
  fs.writeFileSync('user.json', data)
  console.log('JSON data is saved.')
} catch (error) {
  console.error(err)
}

Be careful when you use synchronous file operations in Node.js. The synchronous methods block the Node.js event loop and everything else has to wait for the file operation to be completed.

Read JSON from File

To retrieve and parse JSON data from a file back to a JSON object, you can use the fs.readFile() method along with JSON.parse() for deserialization like below:

const fs = require('fs')

// read JSON object from file
fs.readFile('user.json', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }

  // parse JSON object
  const user = JSON.parse(data.toString())

  // print JSON object
  console.log(user)
})

The above example will output the following on the console:

{ id: 1, name: 'John Doe', age: 22 }

Just like the fs.writeFileSync() method, you can also use fs.readFileSync() to read a file synchronously in a Node.js application.

Take a look how to read and write JSON files in Node.js tutorial to learn more about reading and writing JSON files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.