Back to Homepage
Sunday 11 February 2024
10

How to Read a JSON File with Nodejs

Introduction to Reading JSON Files

Reading JSON files in Node.js is a common task in application development. Node.js provides built-in modules for working with files, making reading JSON files very easy and straightforward.

Using the fs Module to Read JSON Files

The 'fs' (file system) module in Node.js allows us to interact with the machine's file system. To read a JSON file, we first need to import the 'fs' module and then use the 'readFile' method. For example:

const fs = require('fs');

fs.readFile('file.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file', err);
    return;
  }

  console.log('File content:', data);
});

Using the require Function to Load a JSON File

Another common way to read a JSON file in Node.js is by using the 'require' function. This function is usually used to load modules, but it can also load JSON files directly. For example:

const file = require('./file.json');
console.log('File content:', file);
Share:
Created by:
Author photo

Jorge García

Fullstack developer