How to write a JSON object to file in Node.js
By Flavio Copes
Learn how to write a JSON object to a file in Node.js with JSON.stringify() and fs.writeFileSync(), then read it back later using fs.readFileSync().
To write a JSON object to a file in Node.js, turn the object into a string with JSON.stringify(), then write that string to disk with fs.writeFileSync(). Sometimes this is the best way to store some data in a Node.js application, without reaching for a database.
If you need a realistic JSON array to try this with, generate one with my fake data generator.
Writing the file
If you have an object that can be serialized to JSON, you can use the JSON.stringify() method and the fs method fs.writeFileSync() which synchronously writes a piece of data to a file (tip: to check or pretty-print the file you produced, paste it into my JSON formatter):
const fs = require('fs')
const storeData = (data, path) => {
try {
fs.writeFileSync(path, JSON.stringify(data))
} catch (err) {
console.error(err)
}
}
Here’s how you’d use it:
const user = { name: 'Flavio', age: 37 }
storeData(user, './user.json')
This creates a user.json file containing {"name":"Flavio","age":37}.
Note that fs.writeFileSync() overwrites the file if it already exists. There’s no warning. If the old content matters, read it first, or write to a different path.
Pretty-printing the output
By default JSON.stringify() puts everything on one line. Fine for machines, hard for humans.
Pass two extra arguments to get indented output:
fs.writeFileSync(path, JSON.stringify(data, null, 2))
The 2 is the number of spaces used for indentation. Now the file is readable when you open it in your editor.
Reading it back
To retrieve the data, you can use fs.readFileSync():
const loadData = (path) => {
try {
const json = fs.readFileSync(path, 'utf8')
return JSON.parse(json)
} catch (err) {
console.error(err)
return false
}
}
We used a synchronous API, so we can easily return the data once we get it.
The try/catch matters here. JSON.parse() throws if the file content is not valid JSON, and fs.readFileSync() throws if the file doesn’t exist.
Watch out for circular references
Not every object can be serialized. If your object references itself, JSON.stringify() throws a TypeError: Converting circular structure to JSON.
Also, properties whose value is undefined or a function are silently dropped from the output. If you read the file back and something is missing, this is usually why. Store null instead of undefined if you need the key to survive the round trip.
We can also decide to use the asynchronous versions, fs.writeFile and fs.readFile, although the code will change a little bit, and I recommend you take a read at how to write files using Node.js and how to read files using Node.js for this.
Related posts about node: