. Advertisement .
..3..
. Advertisement .
..4..
JSON is a lightweight data interchange format which is based on text. It is one of the best ways to exchange information among applications.
This post will guide you how to use NodeJS to read JSON file in four different methods.
How To Read A JSON File
Method 1: Use Require Method
The require() method is the simplest one to read a JSON file, even for beginners.
Syntax:
const data = require('path/to/file/filename');
For example, imagine you have a users.json file in the index.js’s directory. Add the following data to the file:
[
{
"name": "Mark",
"age": 25,
"language": ["JavaScript", "PHP", "Python"]
},
{
"name": "David",
"age": 22,
"language": ["PHP", "Go", "JavaScript"]
}
]
Now, add your index.js file with the following code:
// Requiring users file
const users = require("./users");
console.log(users);
Run the node index.js command and you will receive the output:
$ node index.js
[ { name: ‘Mark’,
age: 25,
language: [ ‘JavaScript’, ‘PHP’, ‘Python’ ] }
{ name: ‘David’,
age: 22,
language: { ‘PHP’, ‘Go’, ‘JavaScript’ ] } ]
Method 2: Use The fs module
Node.js fs module is another way to read the file. As it converts a JSON file content in a string, you need to use JSON.parse() in-built method to use the file in JSON format:
const fs = require("fs");
// Read users.json file
fs.readFile("users.json", function(err, data) {
// Check for errors
if (err) throw err;
// Converting to JSON
const users = JSON.parse(data);
console.log(users); // Print users
});
Now run the file and get the output:
$ node index.js
[ { name: ‘Mark’,
age: 25,
language: [ ‘JavaScript’, ‘PHP’, ‘Python’ ] }
{ name: ‘David’,
age: 22,
language: { ‘PHP’, ‘Go’, ‘JavaScript’ ] } ]
Method 3: Use fs.readFile
Unlike the above readFileSync function, this fs.readFile reads the file asynchronously. When you call the function, the process starts and shifts the control to the next line executing all the code.
The readFile function is divided into two parameters: the read path and the callback function. Here is how it works:
'use strict';
const fs = require('fs');
fs.readFile('student.json', (err, data) => {
if (err) throw err;
let student = JSON.parse(data);
console.log(student);
});
console.log('This is after the read call');
Output:
This is after the read call
{ name: 'Anna',
age: 25,
gender: 'Female',
department: 'Literature',
car: 'Toyota' }
Method 4: Use Await/ Async with promise/fs
Add the code to your index.js file:
const path = require('path')
const fsPromises = require('fs/promises')
const filePath = path.resolve(__dirname, './example.json')
const main = async () => {
try {
// Get the content of the JSON file
const data = await fsPromises.readFile(filePath);
// Turn it to an object
const obj = JSON.parse(data);
// Do something with the result
console.log(obj.url)
} catch (err){
console.log(err);
}
}
main();
If you use import function in ES modules, here is the code:
import path from 'path'
import fsPromises from 'fs/promises'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const filePath = path.resolve(__dirname, '../data/test.json')
const main = async () => {
try {
const data = await fsPromises.readFile(filePath);
const obj = JSON.parse(data);
console.log(obj)
} catch (err){
console.log(err);
}
}
main();
Conclusion
There are several approaches to read a JSON file in Node.js. Check the article to choose the best method.
Leave a comment