Kinda Code
Home/Node/5 Ways to Read JSON Files in Node.js

5 Ways to Read JSON Files in Node.js

Last updated: February 12, 2023

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 (CommonJS):

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 (CommonJS):

// 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);
  }
})

If you’re using ES Modules, use this code instead:

// index.js
import path from 'path';
import fs from 'fs';

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

onst 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
// CommonJS 
const fs = require('fs')

// using "import" if you're using ES Modules
// import fs from 'fs';

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

console.log(obj.project)

Output:

Kinda Code

Importing JSON Modules

At the time of writing, importing JSON modules is an experimental feature and might change at any time. The syntax is neat and clean:

import data from './example.json' assert { type: 'json' };

console.log(data.project);

Output:

Kinda Code

You might see a warning like this:

(node:11288) ExperimentalWarning: Importing JSON modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

Conclusion

You’ve learned several approaches to extracting content from a JSON file, a place often used to store a small and medium amount of data in projects. 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.