Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to read and write JSON file using Node?
Node.js provides powerful tools for working with files, including reading and writing JSON files. JSON (JavaScript Object Notation) is widely used for storing and exchanging data in applications. This article walks you through reading and writing JSON files in Node.js with examples.
Approaches to Read JSON file
JSON File data.json
{
"name": "PankajBind",
"age": 21,
"skills": ["JavaScript", "Node.js", "React"]
}
Using fs.readFileSync (Synchronous)
The fs module in Node.js provides methods to interact with the file system.
Example
const fs = require('fs');
// Read JSON file synchronously
const data = fs.readFileSync('data.json', 'utf8');
// Parse the JSON string into an object
const jsonData = JSON.parse(data);
console.log("JSON Data:", jsonData);
Output
JSON Data: {
name: 'PankajBind',
age: 21,
skills: [ 'JavaScript', 'Node.js', 'React' ]
}
Using fs.readFile (Asynchronous)
This method is non-blocking and preferred for large files or production environments.
Example
const fs = require('fs');
// Read JSON file asynchronously
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
const jsonData = JSON.parse(data);
console.log("JSON Data:", jsonData);
});
Output
JSON Data: {
name: 'PankajBind',
age: 21,
skills: [ 'JavaScript', 'Node.js', 'React' ]
}
Approaches to Write JSON file
Using fs.writeFileSync (Synchronous)
Use fs.writeFileSync to write data to a JSON file synchronously.
Example
const fs = require('fs');
// Data to write
const data = {
name: "PankajBind",
age: 21,
skills: ["JavaScript", "Node.js", "React"]
};
// Convert object to JSON string
const jsonData = JSON.stringify(data, null, 2);
// Write JSON file synchronously
fs.writeFileSync('output.json', jsonData, 'utf8');
console.log("JSON file has been written.");
Output
{
"name": "PankajBind",
"age": 21,
"skills": [
"JavaScript",
"Node.js",
"React"
]
}
Using fs.writeFile (Asynchronous)
The asynchronous method is non-blocking and suitable for handling large amounts of data.
Example
const fs = require('fs');
// Data to write
const data = {
name: "PankajBind",
age: 21,
skills: ["JavaScript", "Node.js", "React"]
};
// Convert object to JSON string
const jsonData = JSON.stringify(data, null, 2);
// Write JSON file asynchronously
fs.writeFile('output.json', jsonData, 'utf8', (err) => {
if (err) {
console.error("Error writing file:", err);
return;
}
console.log("JSON file has been written.");
});
Output
{
"name": "PankajBind",
"age": 21,
"skills": [
"JavaScript",
"Node.js",
"React"
]
} Advertisements
