Languages
[Edit]
EN

Node.js - read JSON files

3 points
Created by:
Welsh
772

In this article, we would like to show you how to read JSON files in Node.js.

Quick solution:

const fs = require('fs');

try {
    const fileJson = fs.readFileSync('/path/to/file.json', 'utf-8');
    const fileData = JSON.parse(fileJson);
    console.log(fileData);
} catch (ex) {
    console.error(ex);
}

Example preview:

JSON file reading example under Node.js.
JSON file reading example under Node.js.

 

In the below, we present 3 methods to read JSON files:

  • synchronously,
  • asynchronously with callbacks,
  • asynchronously with async/await keywords.

Synchronously

Is recommended to use synchronous operations when we want to get better performance - e.g. Node JS-based sequential scripts run under the operating system.

const fs = require('fs');

const readJsonFile = (path) => {
    const fileJson = fs.readFileSync(path, 'utf-8');
    const fileData = JSON.parse(fileJson);
    return fileData;
};


// Usage example:

const fileData = readJsonFile('/path/to/file.json');

console.log(fileData);

Asynchronously with callback

This approach is commonly used in Node.js web applications.

const fs = require('fs');

const readJsonFile = (path, callback) => {
    fs.readFile(path, 'utf-8', (error, fileJson) => {
        if (error) {
            callback(error, undefined);
        } else {
            try {
                const fileData = JSON.parse(fileJson);
                callback(undefined, fileData);
            } catch (ex) {
                callback(ex, undefined);
            }
        }
    });
};


// Usage example:

readJsonFile('/path/to/file.json', (error, fileData) => {
    if (error) {
        console.log(error);
    } else {
        console.log(fileData);
    }
});

Asynchronously with async/await

The main advantage of this approach is source code readability.

const { readFile } = require('fs/promises');

const readJsonFile = async (path) => {
    const jsonData = await readFile(path, 'utf-8');
    const parsedData = JSON.parse(jsonData);
    return parsedData;
};


// Usage example 1:

const someMethod = async () => {
    try {
        const fileData = await readJsonFile('/path/to/file.json');
        console.log(fileData);
    } catch (ex) {
        console.error(ex);
    }
};

someMethod();


// Usage example 2:

readJsonFile('/path/to/file.json')
    .then((fileData) => console.log(fileData))
    .catch((ex) => console.error(ex));

Alternative titles

  1. Node.js - how to read JSON file
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join