DEV Community

tejesh p
tejesh p

Posted on

NodeJS require() vs fs.readFileSync to read JSON files

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'))

Top comments (1)

Collapse
 
michaelmior profile image
Michael Mior

It's also worth noting that you should never use require to load JSON if you don't trust the source, since it's possible that what you expect to be JSON could actually be JavaScript code that will get executed.