Node.js Write JSON Object to File
To write a JSON object to a file in Node.js, convert the object into a JSON string with JSON.stringify(), then save that string with the fs.writeFile() method from the Node.js file system module. This is useful when you want to store configuration data, API results, application state, logs, or generated output as a .json file.
Node.js Write JSON Object to File – In this tutorial, we shall learn how to write a JSON Object to a local file.
Basic Node.js Steps to Save a JSON Object in a File
To write a JSON Object to a local file, following is a step-by-step guide :
- Create or receive a JavaScript object. If your data is currently a JSON string, parse it first with
JSON.parse(jsonString). - Stringify JSON Object.
Use JSON.stringify(jsonObject) to convert JSON Object to JSON String. - Write the stringified object to file using fs.writeFile() function of Node FS module.
- Handle the callback error so that permission issues, invalid paths, or disk write failures are not missed.
The important point is that fs.writeFile() writes text or binary data. A JavaScript object must be converted to a string before it is written as valid JSON.
Example 1 – Write JSON Object to File in Node.js
In the following Nodejs script, we have JSON data stored as string in variable jsonData. We then used JSON.parse() function to JSONify the string. So now we have a JSON object. Until now we simulated the situation where you have obtained or created a JSON object.
We would like to save this JSON object to a file.
To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS’s writeFile() function.
nodejs-write-json-object-to-file.js
// file system module to perform file operations
const fs = require('fs');
// json data
var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';
// parse json
var jsonObj = JSON.parse(jsonData);
console.log(jsonObj);
// stringify JSON Object
var jsonContent = JSON.stringify(jsonObj);
console.log(jsonContent);
fs.writeFile("output.json", jsonContent, 'utf8', function (err) {
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
console.log("JSON file has been saved.");
});
Useful Link – To access elements of JSON Object, refer Node.js Parse JSON.
Run the above program in Terminal with node command
$ node nodejs-write-json-object-to-file.js
{ persons:
[ { name: 'John', city: 'New York' },
{ name: 'Phil', city: 'Ohio' } ] }
{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}
JSON file has been saved.
output.json File Created by the Node.js Script
After the script runs successfully, Node.js creates an output.json file in the same directory from which you run the command. The file contains the JSON string written by fs.writeFile().
{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}
Write Pretty Formatted JSON to a File in Node.js
The first example writes compact JSON. Compact JSON is valid, but it can be difficult to read in a text editor. To create an indented JSON file, pass spacing arguments to JSON.stringify().
const fs = require('fs');
const user = {
name: 'John',
city: 'New York',
active: true
};
const jsonContent = JSON.stringify(user, null, 2);
fs.writeFile('user.json', jsonContent, 'utf8', (err) => {
if (err) {
console.error('Failed to write JSON file:', err);
return;
}
console.log('user.json has been saved.');
});
In JSON.stringify(user, null, 2), the third argument adds two spaces of indentation. The resulting file remains valid JSON, but it is easier to review and edit manually.
{
"name": "John",
"city": "New York",
"active": true
}
Write a JSON Object with async/await in Modern Node.js
If your Node.js code already uses promises or async functions, use fs.promises.writeFile(). The same rule applies: stringify the object before writing it to the file.
const fs = require('fs/promises');
async function saveJsonFile() {
const settings = {
theme: 'dark',
notifications: true,
itemsPerPage: 20
};
const jsonContent = JSON.stringify(settings, null, 2);
try {
await fs.writeFile('settings.json', jsonContent, 'utf8');
console.log('settings.json has been saved.');
} catch (err) {
console.error('Failed to write settings.json:', err);
}
}
saveJsonFile();
This form is often cleaner when the write operation is part of a longer asynchronous workflow, such as reading data from an API and saving the response as JSON.
Append or Update Data in an Existing JSON File
JSON files are normally rewritten after changes. To add a new item to an existing JSON file, read the file, parse the existing JSON, update the JavaScript object or array, stringify it again, and then write it back.
const fs = require('fs/promises');
async function addPerson() {
const filePath = 'people.json';
try {
const fileContent = await fs.readFile(filePath, 'utf8');
const data = JSON.parse(fileContent);
data.persons.push({
name: 'Sara',
city: 'Boston'
});
await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf8');
console.log('people.json has been updated.');
} catch (err) {
console.error('Could not update JSON file:', err);
}
}
addPerson();
This approach works when the file contains valid JSON, such as an object with a persons array. If the file is empty, missing, or malformed, JSON.parse() will throw an error, so handle that case in production code.
A Big Note
In the above program, you might have observed that both jsonData and jsonContent when logged to console result in same output. This is because when the JSON Object is logged to console, toString method is called implicitly. But if you attempt to write the JSON object to a file directly without prior Stringify, it results in [Object Object] written to file.
The mistake usually happens in code like the following, where the object is passed directly to writeFile() instead of passing a JSON string.
const fs = require('fs');
const user = {
name: 'John',
city: 'New York'
};
// Do not do this.
fs.writeFile('user.json', user, 'utf8', (err) => {
if (err) {
console.error(err);
}
});
Use JSON.stringify(user) or JSON.stringify(user, null, 2) instead. That conversion is what makes the file content valid JSON.
fs.writeFile() vs fs.writeFileSync() for JSON Files
For most Node.js applications, prefer fs.writeFile() or fs.promises.writeFile() because they do not block the event loop while the file operation is running. fs.writeFileSync() is simpler for small scripts, command-line utilities, and setup files, but it blocks execution until the file write completes.
const fs = require('fs');
const config = {
port: 3000,
environment: 'development'
};
fs.writeFileSync('config.json', JSON.stringify(config, null, 2), 'utf8');
console.log('config.json has been saved.');
Use the synchronous version only when blocking behavior is acceptable. In a server route, API handler, or long-running service, the asynchronous version is usually the better choice.
Common Errors When Writing JSON Files in Node.js
- Writing
[object Object]: This happens when a JavaScript object is written directly. UseJSON.stringify(). - Invalid file path: Check whether the directory exists before writing the file.
- Permission denied: The Node.js process must have permission to write in the target directory.
- Malformed existing JSON: If you read and update an existing file,
JSON.parse()fails when the file does not contain valid JSON. - Overwriting existing data:
fs.writeFile()replaces the file content. Read and merge old data first if you want to preserve it.
FAQs on Writing JSON Object to File in Node.js
How do I write a JSON object to a file in Node.js?
Use JSON.stringify() to convert the JavaScript object into a JSON string, then pass that string to fs.writeFile() or fs.promises.writeFile().
How do I write formatted JSON instead of one-line JSON?
Use JSON.stringify(object, null, 2). The third argument adds indentation, so the saved JSON file is easier to read.
Why does my JSON file contain [object Object]?
That usually means the JavaScript object was written directly to the file. Convert it first with JSON.stringify(object).
How do I update an existing JSON file in Node.js?
Read the file with fs.readFile(), parse it with JSON.parse(), change the object or array, then write the updated JSON string back to the file.
Should I use writeFile or writeFileSync for saving JSON?
Use writeFile() or fs.promises.writeFile() for most applications because they are asynchronous. Use writeFileSync() only for small scripts where blocking execution is acceptable.
Editorial QA Checklist for Node.js JSON File Writing Examples
- Verify that every example converts the object with
JSON.stringify()before writing the file. - Confirm that callback, promise, and synchronous examples use the correct Node.js
fsAPI. - Check that output examples show valid JSON, not JavaScript object notation.
- Make sure update examples read, parse, modify, stringify, and rewrite the JSON file in that order.
- Confirm that code blocks use the correct PrismJS language class for JavaScript, Bash commands, and output.
Concluding this Node.js Tutorial – Node.js Write JSON Object to File, we have learned to write a JSON Object to a file using JSON.stringify() function and FS.writeFile() function. We also covered pretty formatting, promise-based file writing, updating an existing JSON file, and the common mistake that writes [object Object] instead of valid JSON.
TutorialKart.com