How to save JSON data to a file in Node.js

Mateen Kiani

Mateen Kiani

Published on Sun Sep 24 2023·3 min read

node.js

Node.js, with its built-in modules, provides a straightforward way to work with files, including saving JSON data. Whether you're building a configuration manager, a data storage system, or simply need to persist data to a file, Node.js makes it easy. In this article, we'll explore the steps to save JSON data to a file in Node.js.

Setting up Your Node.js Environment

Before we dive into saving JSON data to a file, ensure you have Node.js installed on your system. You can download it from the official Node.js website.

Creating JSON Data

Let's start by creating some JSON data that we want to save. For this example, we'll use a simple JavaScript object representing a user profile.

const userProfile = {
username: 'jsmith',
email: 'jsmith@example.com',
age: 30,
hobbies: ['reading', 'gaming', 'coding'],
};

Using the fs Module

Node.js includes a core module called fs (File System) that allows you to work with files. We'll use this module to save our JSON data to a file.

First, require the fs module at the beginning of your script:

const fs = require('fs');

Stringify JSON Data

To save JSON data to a file, we need to convert our JavaScript object into a JSON string using the JSON.stringify() method.

const jsonData = JSON.stringify(userProfile);

Specifying the File Path

Choose a file path and name where you want to save your JSON data. For example, let's save our user profile data to a file named user_profile.json in the same directory as our script:

const filePath = 'user_profile.json';

Writing to the File

Now, use the fs.writeFileSync() method to write the JSON data to the file:

try {
fs.writeFileSync(filePath, jsonData);
console.log('JSON data saved to file successfully.');
} catch (error) {
console.error('Error writing JSON data to file:', error);
}

The fs.writeFileSync() method writes the data synchronously to the file. If the file does not exist, it will be created. If it does exist, the data will be overwritten.

Running the Script

Save your script with a .js extension (e.g., saveToJson.js) and run it using Node.js:

node saveToJson.js

Verification

After running the script, you will see following output in console:

Data saved to JSON file successfully.

Now check the same directory where your script is located. You should find a file named user_profile.json containing your JSON data.

Output in string form

If you open the file user_profile.json, you'll notice that the data is saved in string form:

{"username":"jsmith","email":"jsmith@example.com","age":30,"hobbies":["reading","gaming","coding"]}

Saving Pretty-Printed JSON Data

If you want to save the data in a pretty-printed format, you can modify the code as follows:

const prettyJsonData = JSON.stringify(userProfile, null, 2);
fs.writeFileSync('pretty_user_profile.json', prettyJsonData);

This code uses JSON.stringify() with the space parameter set to 2 for indentation.

Result

After running the script with pretty-printed data, check the same directory where your script is located. You should find a file named pretty_user_profile.json containing your JSON data in a nicely formatted way:

{
"username": "jsmith",
"email": "jsmith@example.com",
"age": 30,
"hobbies": [
"reading",
"gaming",
"coding"
]
}

Conclusion

In Node.js, saving JSON data to a file is a straightforward process. By using the fs module, you can convert your JavaScript objects into JSON strings and write them to files for later retrieval or storage. This capability is useful for creating configuration files, saving user preferences, or persisting data for your Node.js applications.

Remember to handle errors gracefully, especially when working with file operations, and consider using asynchronous file writing methods if you need to avoid blocking your application's execution. With Node.js, you have the tools you need to work with JSON data and files efficiently.

If you have any question let me know in the comments section.


Mateen Kiani
Mateen Kiani
kiani.mateen012@gmail.com
I am a passionate Full stack developer with around 3 years of experience in MERN stack development and 1 year experience in blockchain application development. I have completed several projects in MERN stack, Nextjs and blockchain, including some NFT marketplaces. I have vast experience in Node js, Express, React and Redux.