Loading episodes…
0:00 0:00

Read JSON Files In NodeJS With require() and fs.readFileSync()

00:00
BACK TO HOME

Read JSON Files In NodeJS With require() and fs.readFileSync()

10xTeam September 01, 2020 1 min read

In Node.js you have two methods for reading JSON files require() and fs.readFileSync().

For static JSON files, use the require() method because it caches the file. but for dynamic JSON file the fs.readFileSync() is preferred.

After reading the JSON file using fs.readFileSync() method, you need to parse the JSON data using the JSON.parse() method.

Using the require method, you can read your JSON file in one line of code as follows:

let data = require('./file.json')

Using the fs.readFileSync() method, you cann read the file in two lines of code:

const fs = require('fs')
let data = JSON.parse(fs.readFileSync('file.json', 'utf-8'))

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?