How to Update Data in JSON File using Node?
Last Updated :
24 Oct, 2024
To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file.
Using require() Method
This is a direct approach to update the json data. We will use require() method to import the JSON file and read it as JavaScript object. Then directly update the required values. Update the data back to the file synchronously using the writeFileSync() method.
Syntax
const fs = require('fs');
// Read the JSON file using require
const jsonData = require('./data.json');
// Update the data
jsonData.key = 'new value';
// Synchronously write the updated data back to the JSON file
fs.writeFileSync('./data.json', JSON.stringify(jsonData, null, 2));
console.log('Data updated successfully.');
Before Updating data.json file
{
"key": "old value"
}
After Updating data.json file
{
"key": "new value"
}
Steps to create Node.js Application
Step 1: Create a a folder for your application and move to that folder using below command.
cd foldername
Step 2: Create a NodeJS application using the following command:
npm init
Example : The below example demonstrate updating data in json file using require() method
JavaScript
// Filename: index.js
const fs = require('fs');
// Read the JSON file
const jsonDataBefore = require('./data.json');
// Print JSON data before updating
console.log('Before updating JSON:');
console.log(JSON.stringify(jsonDataBefore, null, 2));
// Update the data
jsonDataBefore[0].programmingLanguage.push("JavaScript");
jsonDataBefore[1].programmingLanguage.push("JavaScript");
// Write the updated data back to the JSON file
fs.writeFileSync('./data.json', JSON.stringify(jsonDataBefore, null, 2));
// Print JSON data after updating
console.log('\nAfter updating JSON:');
console.log(JSON.stringify(jsonDataBefore));
console.log('\nData updated successfully.');
JavaScript
//File path: data.json (note: remove this comment line)
[
{ "name": "John", "programmingLanguage": ["Python"] },
{ "name": "Alice", "programmingLanguage": ["C++"] }
]
To run the application use the following command
node index.js
Output
Before updating JSON:
[
{
"name": "John",
"programmingLanguage": [
"Python"
]
},
{
"name": "Alice",
"programmingLanguage": [
"C++"
]
}
]
After updating JSON:
[
{
"name": "John",
"programmingLanguage": [
"Python",
"JavaScript"
]
},
{
"name": "Alice",
"programmingLanguage": [
"C++",
"JavaScript"
]
}
]
Data updated successfully.
Using File System Module
Updating a JSON file in Node.js using the filesystem module we will
- Read the JSON file using fs.readFile method.
- Then parse data to JavaScript object using JSON.parse.
- Update the values in object.
- Convert the updated object back to a JSON string using JSON.stringify.
- Write the updated JSON string back to the file using fs.writeFile.
Syntax
const fs = require('fs');
// Read the JSON file
let rawData = fs.readFile('data.json');
let jsonData = JSON.parse(rawData);
// Update the data
jsonData.key = 'new value';
// Write the updated data back to the file
fs.writeFilec('data.json', JSON.stringify(jsonData));
Before Updating data.json file
{
"key": "old value"
}
After Updating data.json file
{
"key": "new value"
}
Example: Updating data in json file using file system module.
JavaScript
//File path: /index.js
const fs = require('fs');
// Define the file path
const filePath = 'data.json';
// Read the JSON file
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
try {
// Parse the JSON data
const jsonData = JSON.parse(data);
// Display the original data
console.log('Before updating JSON:');
console.log(jsonData);
// Update the data
jsonData.forEach(item => {
item.programmingLanguage.push('JavaScript');
});
// Display the updated data
console.log('\nAfter updating JSON:');
console.log(jsonData);
// Write the updated data back to the file
fs.writeFile(filePath, JSON.stringify(jsonData), (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('\nData updated successfully.');
});
} catch (error) {
console.error('Error parsing JSON data:', error);
}
});
JavaScript
//File path: data.json (note: remove this comment line)
[
{ "name": "John", "programmingLanguage": ["Python"] },
{ "name": "Alice", "programmingLanguage": ["C++"] }
]
To run the application use the following command
node index.js
Output
Before updating JSON:
[
{ name: 'John', programmingLanguage: [ 'Python' ] },
{ name: 'Alice', programmingLanguage: [ 'C++' ] }
]
After updating JSON:
[
{ name: 'John', programmingLanguage: [ 'Python', 'JavaScript' ] },
{ name: 'Alice', programmingLanguage: [ 'C++', 'JavaScript' ] }
]
Data updated successfully.
Similar Reads
How to Add Data in JSON File using Node.js ?
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to update data in sqlite3 using Node.js ?
In this article, we are going to see how to update data in the sqlite3 database using node.js. So for this, we are going to use the run function which is available in sqlite3. This function will help us to run the queries for updating the data. SQLite is a self-contained, high-reliability, embedded,
4 min read
How to Update Data in JSON File using JavaScript ?
To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of Content Using require() M
4 min read
How to truncate a file using Node.js ?
In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js ca
3 min read
How to Download a File Using Node.js?
Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries. Usin
3 min read
How to Upload File using formidable module in Node.js ?
A formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads. ApproachTo upload file using the formidable module in node we will first install formidable. Then create an HTTP server to a
2 min read
How to Get Data from MongoDB using Node.js?
One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
3 min read
How to read and write files in Node JS ?
NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to work with Node.js and JSON file ?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
4 min read