How to Add Data in JSON File using Node.js ?
Last Updated :
08 Jan, 2025
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:
Approach
To add data in JSON file using the node js we will be using the fs module in node js. We will first get the data from file using fs.readFileSync and store in an object. Then push the new data and write the data using fs.writeFile method to the given json file.
Steps to Add Data in JSON file using Node
Step 1: Import the fs (file system) module
First of all, you need to ensure that the JSON file that you are expecting is not going to consume a large memory. For data that is estimated to consume around 500MB, this method won't be efficient and you should rather consider using a database system.
Node.js has an in-built module named fs, which stands for File System and enables the user to interact with the file system in a modeled way. To use it, type the code below in your server program.
const fs = require('fs');
To know more about fs module visit
here.
Step 2: Create a Sample Data
We can start by creating a JSON file, which will contain an id, a name and a city for this example.Note that you can have as many key-value pairs as you want, but we are using three here for a start.
{
"id": 1,
"name": "John",
"city": "London"
}
Let's name this JSON file as data.json.
Step 3: Read and Process the Sample Data
Now that we have a JSON file to write to, first we will make a JavaScript object to access the file.For this, we will use fs.readFileSync() which will give us the data in raw format. To get the data in JSON format, we will use JSON.parse().Thus, the code on our server side will look like this:
var data = fs.readFileSync('data.json');
var myObject= JSON.parse(data);
Step 4: Prepare and Push new Data
Now that we have our object ready, let's suppose we have a key-value pair of data that we want to add :
let newData = {
"country": "England"
}
We need to use our object(i.e. myObject) to add this data.We will do this by using .push() method as follows: Note: To use push() function, data objects in json file must be stored in array. If JSON file is empty or having single object without array, push() will give error.
myObject.push(newData);
Step 5: Stringify and Write the data to JSON file
To write this new data to our JSON file, we will use fs.writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it. This will be done using JSON.stringify() method.
var newData = JSON.stringify(myObject);
fs.writeFile('data.json', newData, err => {
// error checking
if(err) throw err;
console.log("New data added");
});
Step 6: Verify the Updated Data
Now our data.json file would look like this:
{
"id": 1,
"name": "John",
"city": "London",
"country": "England"
}
Example: This example demonstrate the above approach to add data to json file using Nodejs.
Node
// Filename - index.js
// Requiring fs module
const fs = require("fs");
// Storing the JSON format data in myObject
var data = fs.readFileSync("data.json");
var myObject = JSON.parse(data);
// Defining new data to be added
let newData = {
country: "England",
};
// Adding the new data to our object
myObject.push(newData);
// Writing to our JSON file
var newData2 = JSON.stringify(myObject);
fs.writeFile("data2.json", newData2, (err) => {
// Error checking
if (err) throw err;
console.log("New data added");
});
Output:
Conclusion
In conclusion, using Node.js's fs module, you can efficiently add data to JSON files. By reading, parsing, modifying, and writing back data, you can dynamically update your JSON files. This process ensures your data remains up-to-date and easily accessible, essential for applications requiring persistent data storage and manipulation.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read