4 Ways to Read JSON Files in Node.js

Last updated on November 23, 2021 A Goodman Loading... Post a comment

This article walks you through a bunch of different ways to read JSON files in Node.js. Without any further ado, let’s get our hands dirty by writing some code.

Getting Started

This is the sample JSON file used in the following examples:

{
  "project": "Kinda Code",
  "url": "https://www.kindacode.com",
  "description": "The World Of Code"
}

You can download it here.

Initialize a new npm project by executing:

npm init

Create an empty index.js file and copy the JSON file above (let’s call it example.json) into the project. Here’s the file structure:

.
├── example.json
├── index.js
├── package-lock.json
└── package.json

From now on, we will only touch the index.js file.

Asynchronously Reading JSON File

In modern Node.js applications, you will usually read files asynchronously.

Using Async/Await with fs/promise

Put this code into your index.js file:

const path = require('path')
const fsPromises = require('fs/promises')

const filePath = path.resolve(__dirname, './example.json')

const main = async () => {
  try {
    // Get the content of the JSON file 
    const data = await fsPromises.readFile(filePath);

    // Turn it to an object
    const obj = JSON.parse(data);

    // Do something with the result
    console.log(obj.url)
  } catch (err){
    console.log(err);
  }
}

main();

The preceding code will produce the output below:

https://www.kindacode.com

If you prefer ES Modules (using import instead of require) then the code will be like this:

import path from 'path'
import fsPromises from 'fs/promises'

import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const filePath = path.resolve(__dirname, '../data/test.json')

const main = async () => {
  try {
    const data = await fsPromises.readFile(filePath);
    const obj = JSON.parse(data);
    console.log(obj)
  } catch (err){
    console.log(err);
  }
}

main();

Using fs.readFile

The code:

// index.js
const path = require('path')
const fs = require('fs')

const filePath = path.resolve(__dirname, './example.json')

fs.readFile(filePath, (err, data) => {
  if(err){
    console.log('Something went wrong');
  } else {
    const obj = JSON.parse(data);
    console.log(obj);
  }
})

Output:

{
  project: 'Kinda Code',
  url: 'https://www.kindacode.com',
  description: 'The World Of Code'
}

Synchronously Reading JSON FIle

There might be scenarios you want to get the content of a JSON file synchronously, such as when loading a config file that contains your API keys, database password, etc.

Just requiring the file

The task can be done quickly with only one line of code as follows:

// index.js
const data = require('./example.json');
console.log(data.description)

Output:

The World Of Code

Using fs.readFileSync

An alternative technique with the fs module:

// index.js
const fs = require('fs')

const data = fs.readFileSync('./example.json')
const obj = JSON.parse(data)

console.log(obj.project)

Output:

Kinda Code

Conclsuion

You’ve learned several approaches to extracting content from a JSON file. If you would like to explore more new and interesting stuff about modern Node.js, take a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles