Introduction
The JSON (Javascript Object Notation) format is one of the most acceptable ways to share data between applications written in various languages.
JSON files are a convenient and straightforward way to store data between server restarts with Node. Node provides some built-in utilities that make it easy to read/write JSON files, whether reading a file or persisting data for the application.
JSON File
Let's create a JSON file that holds a record for a student in your class.
The file stores the name, age, gender, and the department of the student.
The file will be as follows: "student.json."
Now save this file as "student.json" in the project directory.
{ "name": "Sarah", "age": 22, "gender": "Female", "department": "Computer Science" } |
Reading a JSON File
Method 1:
Using the require method: The simplest way is to use the global require to read and parse the JSON files in a node.js.
Syntax:
const data = require('path/to/file/filename'); |
Have a look at the following example.
Now, add the below code to your index.js file.
const jsonData = require('./student.json'); console.log(jsonData); |
Now, run the using the command:
node index.js |
Output:
This method can be used anywhere, which has its advantages.
However, there are a few disadvantages of using the require function:
- Require is a synchronous function that is only called once, resulting in a cached result for the calls. You can't use this approach to re-read a file that has been modified.
- Your file must have a '.json' extension, so it can't be as flexible. Without the proper extension required, it doesn't treat the file as a JSON file.
Method 2:
The fs module:
The 'fs' module returns a file content in string format, converting it into JSON format using the in-built JSON.parse() method.
There are two functions available in the fs module that we can use: readFile and readFileSync.
Using fs.readFileSync
The readFileSync function synchronously reads the data. This function prevents the rest of the code from being executed until all of the data from the file has been read. This function is only useful when your application has to perform configuration settings before doing any other tasks.
Using fs.readFile
Unlike the readFileSync function, the readFile function asynchronously reads the file data. When the readFile function is called, the file reading process begins, and control shifts instantly to the next line when the following lines of code are executed. This function will call the given callback function once the file data has been loaded. This way, you won't be blocking code execution while waiting for the operating system to respond with data.
In the given example, the readFile function takes two parameters: The path to the JSON file and the callback function to be called when the file is read completely. You can also include a parameter with options, but we won't be covering those in this article. Add the following code in the index.js file:
const fs = require("fs");
|
Now rerun the index.js file, and you'll see an output like this:
Output:
Here,
- (err, data) => {}: This is the provided callback function that is executed once the file is thoroughly read.
- err: Since asynchronous programming makes it difficult to utilize try/catch, the function returns an err object if something goes wrong. If there were no errors, it is null.
You may have also noticed that just after running readFile, we print a string to the console. This is to show how asynchronous code works. When you run the above script, you'll notice that the console.log method runs before the readFile callback function. This is because readFile does not prevent code from running while reading data from the file system.
Write to a JSON File
Similar to the read methods, there are two functions for writing data to files: writeFile and writeFileSync. The writeFile method, as its name implies, writes data to a file in an asynchronous manner while the writeFileSync function writes data to a file synchronously.
We can use the fs module to write data into a JSON file. Use the writeFile method to write data into a file.
Using writeFileSync
The writeFileSync function can accept 2-3 parameters: The path of the file to write data to, the data to write, and an optional argument.
Note: If the file doesn't exist, then a new file is created. For example, run the below-written code.
const fs = require('fs'); let student = { name: 'John', age: 20, gender: 'Male', department: 'Computer Science', }; let data = JSON.stringify(student); fs.writeFileSync('student-2.json', data); |
In the above example, we have saved the JSON object student to a file called "student-2.json". Here we have to use the JSON.stringify function before saving the data. We must "stringify" the data before storing it in a string form in the file, just as we had to parse the data into JSON format while reading the JSON file.
Run the above code and open the "student-2.json" file. You should see the following content in the file:
Here, the data is in the form of a single line of string, making it difficult to read. Let's change it to be a human-readable form. Here's how to use the stringify function for this:
let data = JSON.stringify(student, null, 2); |
Here we tell the method to add new lines and a couple of indentations to the serialized JSON. Now open the "student-2.json" file. You should see the output in the following format.
Using fs.writeFile
As mentioned earlier, the writeFile function is asynchronous, which means that our code will not be blocked while data is written to the file. We must also pass a callback to this function, exactly as we previously did with the asynchronous methods.
Let's use the writeFile function to create a new file called "student-3.json."
const fs = require('fs'); let student = { name: 'Mike', age: 23, gender: 'Male', department: 'English', car: 'Honda' }; let data = JSON.stringify(student, null, 2); fs.writeFile('student-3.json', data, (err) => { if (err) throw err; console.log('Data written to file'); }); console.log('This is after the write call'); |
Output:
Because our callback hasn't'' been triggered yet, you can see that the last line of our code appears first in the console. If you have a significant amount of data to write to your file or a lot of files to write to, this will save you a lot of time.
Also see, Difference Between Controller and Restcontroller
FAQs
-
What is a JSON file?
JSON ( JavaScript Object Notation) is a light-weight, text-based data-interchange format. Like XML, it is one of the methods for transferring information across apps. Web applications or APIs widely use this format.
-
What does res JSON () do?
The res.json() function is used to send a JSON response. This function returns a response that is the parameter converted to a JSON string using the JSON method.
-
How do I parse a JSON array in node JS?
For parsing JSON data in Node.js, we can use the JSON.parse() function of JavaScript Engine. Click to know more.