Matt Stephens Matt Stephens - 6 months ago 19
Node.js Question

fs vs require JSON

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?

Answer

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.

Comments