I'll start of with saying I'm new to NodeJS but i've been developing in PHP for a number of years (doesn't mean much I know).
I started tinkering with Node recently and discovered something strange I hope someone can help with
I have a file call local.js
this pulls in a .JSON
file that is used to setting such as oAuth keys
and the like.
The initial way I pulled this file in was like:
var fs = require('fs')
var settings = fs.readFileSync('./config/settings.json', 'utf8')
What I found was that I wouldn't be able to read a value from the JSON
in settings
via settings.key
this would give me undefined
Testing out another method below
var settings = require('./config/settings.json')
Allows me to read the value from the JSON
via settings.key
I was wonder why this is the case?
If your file does not have a .json extension, require will not treat the contents of the file as JSON. Show activity on this post. I suppose you'll JSON.parse the json file for the comparison, in that case, require is better because it'll parse the file right away and it's sync:
require is synchronous and only reads the file once, following calls return the result from cache. If your file does not have a .json extension, require will not treat the contents of the file as JSON.
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.
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:
fs.readFileSync()
just reads the data contained in the file, but it doesn't parse it.
For that, you need an additional step:
var settings = JSON.parse( fs.readFileSync('./config/settings.json', 'utf8') );
Using require()
will parse the data automatically.
Function fs.readFileSync()
reads only the contents of file as a string.
While require()
will read the contents of file as well as parse it using JSON.parse()
function so you will get a json object in return.
Its better to use require()
if you are not modifying the json file in between your execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With