Multiple ways to read local json file in Nodejs application


In this tutorial, multiple ways to read local json file in Nodejs application

  • using required js
  • fs module readFile

Let’s declare an local json file in the nodejs project emp.json

{
"id": 1,
"name": "John",
"salary": 5000
}

easy way to read local json file with require function in nodejs

This is an simple and easy way to read using require function

const json = require("./emp.json");
console.log(json);

It directly reads file as an object from local file. Notes:

  • It is simple and easy to read
  • During application running, It only read the content on the file but not read the modified content. You need to restart the server to reload modified content from local json file.

Nodejs provides built in fs module to work with file system. Reading file in json involves in two ways

  • synchronous with readFileSync
  • asynchronous with readFile

Let’s see code with nodejs fs module read file example

How to read local json as a string in nodejs

fs module has readFileSync method

syntax

fs.readFileSync( filepath, fileoptions )

Parameters are path of a file and options are optional configuration like encoding details.

const fs = require("fs");
const data = fs.readFileSync('./emp.json', 'utf8');
console.log(data);

Output

{
"id": 1,
"name": "John",
"salary": 5000
}
{ id: 1, name: 'John', salary: 5000 }

Here are following steps to read local json file

  • First Import fs module into your js file readjson.js
  • call readFileSync method with path of the file and encoding details
  • log the json content into console

Notes with this approach

  • It reads during code execution and changes to json file are reloaded and read as expected
  • It is synchronous of reading file, Performance is not good and current thread waits for an reading to complete it.
  • It is not suitable for reading large file as file content are read into memory.

Asynchronous reading local json file using nodejs fs module

This is asynchronous way of reading json file from file system.

  • Import fs module into code using require function
    • nodejs fs filesystem module has readFile method which asynchronously read the path of local json file and returns callbacks
  • Callbacks contains two parameters, One is error and another is string object, error object contains an error if an error occurs, string objects read the json content into an string.
  • Finally parse string object to convert into of type Object using json.parse() method
  • finally convert the string into object and wraps parsing error results in try and catch block
 const fs = require("fs");
fs.readFile('./emp.json', 'utf8', (err, jsonObject) => {
    if (err) {
        console.log('Error callback:', err);
        return;
    }
    try {
        console.log(jsonObject); // string object 
        const jsonData = JSON.parse(jsonObject);
        console.log(jsonData); //object type
    } catch (err) {
        console.log('Error while parsing JSON string data:', err);
    }
})

Notes:

  • This is best and real time way of reading files
  • Current thread will not wait for reading file operation is completed.

Conclusion

You learned multiple ways of reading local json file in nodejs application

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.