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
- Node
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.
// 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.