Read JSON File in Node.js – A Step-by-Step Tutorial

In today’s full-stack development landscape, being able to read JSON file in Node.js is a critical skill for backend developers. JSON (JavaScript Object Notation) has become the backbone of data interchange on the web. Node.js, with its non-blocking I/O and event-driven architecture, provides several ways to handle JSON data effectively. This guide will walk you through how to read JSON file in Node.js, ensuring you have the techniques necessary for your projects.

Read JSON File in Node.js

Table of Contents

Prerequisites

Before proceeding with the examples, ensure that you have Node.js installed on your system. You can download and install Node.js from their official website. A basic understanding of JavaScript and familiarity with the Node.js runtime environment is also expected.

 

Read JSON File Synchronously

A synchronous read operation in Node.js actively halts the execution of other code until the file reading process is finished. During this blocking operation, no further code is processed, which can lead to delays and reduced application responsiveness. To perform synchronous reads, you use Node.js file system (fs) functions that provide this blocking behavior.

const fs = require('fs');

function readJsonFileSync(filePath) {
    let rawdata = fs.readFileSync(filePath);
    let jsonData = JSON.parse(rawdata);
    console.log(jsonData);
    return jsonData;
}

// Call the function with the path to your JSON file
readJsonFileSync('path/to/your/file.json');

Output:

{
  "name": "Example",
  "version": "1.0.0"
}

In this example, we import the fs module and use its readFileSync function to read the contents of the specified JSON file. We then parse this data using JSON.parse to convert the string into a JavaScript object. It’s important to handle exceptions that may occur, such as a file not being found or the JSON being malformed.

 

Read JSON File Asynchronously

Asynchronous operations in Node.js actively enable concurrent execution of other code while awaiting the completion of file reading, harnessing the full potential of Node’s capabilities. This non-blocking approach enhances application responsiveness and efficiency, as it allows multiple tasks to progress simultaneously. Developers can leverage asynchronous file operations using callbacks or promises, ensuring a more responsive and responsive application design.

const fs = require('fs');

function readJsonFileAsync(filePath) {
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return;
        }
        let jsonData = JSON.parse(data);
        console.log(jsonData);
    });
}

// Call the function with the path to your JSON file
readJsonFileAsync('path/to/your/file.json');

Output:

{
  "name": "Async Example",
  "version": "2.0.0"
}

This example demonstrates the asynchronous variant using fs.readFile. A callback function is provided, which is called once the file has been read. The callback handles errors and parses the JSON content. This is the preferred method to read JSON in Node.js because it doesn’t block the event loop.

 

Handling Errors

Error handling is crucial when dealing with file operations. Errors can be due to missing files, lack of permissions, or parsing errors, and should be handled gracefully. Here is an example of how you can handle errors in asynchronous reads:

const fs = require('fs');

function safeReadJsonFileAsync(filePath) {
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            console.error(`Error reading file from disk: ${err}`);
        } else {
            try {
                const jsonData = JSON.parse(data);
                console.log(jsonData);
            } catch (err) {
                console.error(`Error parsing JSON string: ${err}`);
            }
        }
    });
}

// Call the function with the path to your JSON file
safeReadJsonFileAsync('path/to/your/file.json');

Output:

{
  "name": "Safe Async Example",
  "version": "3.0.0"
}

Here we’ve added try…catch blocks inside the callback function to handle JSON parsing errors. The console’s error method is used to print out any errors encountered.

 

Summary

This tutorial provided a comprehensive guide to reading JSON files in Node.js. We covered both synchronous and asynchronous methods, showing their respective benefits and use cases. With proper error handling demonstrated, you now have the tools to read JSON data effectively and safely in your Node.js applications. Remember, asynchronicity is key to leveraging Node.js’s strengths, and thus, asynchronous reading methods are generally preferred.

References