How to read and write JSON file using Node.js ?
Node.js is an open source and cross-platform runtime environment for executing JavaScript code outside of the browser. It is widely used in developing APIs and microservices from small to large companies.
JSON or JavaScript Object Notation is a light weight, text-based data interchange format. Like XML, it is one of the way of exchanging information between applications. This format of data is widely used by web applications/APIs to communicate with each other.
Reading a JSON file:
- Method 1: Using require method: The simplest method to read a JSON file is to require it in a node.js file using
require()
method.Syntax:
const data = require('path/to/file/filename');
Example: Create a users.json file in the same directory where index.js file present. Add following data to the json file.
users.json file:
[
{
"name"
:
"John"
,
"age"
: 21,
"language"
: [
"JavaScript"
,
"PHP"
,
"Python"
]
},
{
"name"
:
"Smith"
,
"age"
: 25,
"language"
: [
"PHP"
,
"Go"
,
"JavaScript"
]
}
]
Now, add the following code to your
index.js
file.index.js file:
// Requiring users file
const users = require(
"./users"
);
console.log(users);
Now, run the file using the command:
node index.js
Output:
- Method 2: Using the fs module: We can also use node.js fs module to read a file. The
fs
module returns a file content in string format so we need to convert it into JSON format by using JSON.parse() in-built method.
Add the following code into yourindex.js
file:
index.js file:const fs = require(
"fs"
);
// Read users.json file
fs.readFile(
"users.json"
,
function
(err, data) {
// Check for errors
if
(err)
throw
err;
// Converting to JSON
const users = JSON.parse(data);
console.log(users);
// Print users
});
Now run the file again and you’ll see an output like this:
Output:
Writing to a JSON file: We can write data into a JSON file by using the node.js fs module. We can use writeFile method to write data into a file.
Syntax:
fs.writeFile("filename", data, callback);
Example: We will add a new user to the existing JSON file, we have created in the previous example. This task will be completed in three steps:
- Read the file using one of the above methods.
- Add the data using
.push()
method. - Write the new data to the file using
JSON.stringify()
method to convert data into string.
const fs = require( "fs" ); // STEP 1: Reading JSON file const users = require( "./users" ); // Defining new user let user = { name: "New User" , age: 30, language: [ "PHP" , "Go" , "JavaScript" ] }; // STEP 2: Adding new data to users object users.push(user); // STEP 3: Writing to a file fs.writeFile( "users.json" , JSON.stringify(users), err => { // Checking for errors if (err) throw err; console.log( "Done writing" ); // Success }); |
Run the file again and you will see a message into the console:
Now check your users.json file it will looks something like below:
Please Login to comment...