Languages
[Edit]
EN

Node.js - read JSON files

3 points
Created by:
Romany-Welsh
382

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

Below we will present 3 methods to read JSON:

  • synchronously,
  • asynchronously with callback,
  • 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 jsonData = fs.readFileSync('/path/to/file.json');
const parsedData = JSON.parse(jsonData); // json parsed as object

console.log(parsedData);

Asynchronously with callback

Note:

In the fs.readFile() method, we must provide an absolute path to the file.

const fs = require('fs');

fs.readFile('/path/to/file.json', (error, jsonData) => {
    if (error) throw error;
    const parsedData = JSON.parse(jsonData); // json parsed as object
    console.log(parsedData);
});

Asynchronously with async/await

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

const readJSONFileAsync = async (path) => {
    try {
        const jsonData = await readFile(path);
        const parsedData = JSON.parse(jsonData);
        console.log(parsedData);
    } catch (error) {
        console.error(error);
    }
};

readJSONFileAsync('/path/to/file.json');

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