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 (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.