you can read json files either using
require('filename.json')
or
fs.readFileSync('filename.json')
If the JSON file is static,
require()
is better because
require()
caches the file. On the other hand, if the JSON file changes,
fs.readFileSync
is better because reads the file every time and hence useful when the contents of the JSON file have to be re-fetched.
Also, do note that when using
fs.readFileSync
, additionally you have to do JSON.parse after reading the content.
// using require directly to read json
let data = require('./file.json')
// using fs module to read json
const fs = require('fs')
let data = JSON.parse(fs.readFileSync('file.json', 'utf-8'))
Built on Forem — the open source software that powers DEV and other inclusive communities.
Made with love and Ruby on Rails. DEV Community © 2016 - 2024.