Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fs vs require JSON

Tags:

node.js

fs

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?

like image 375
Matt Stephens Avatar asked May 31 '16 09:05

Matt Stephens


People also ask

Why doesn't require work with JSON files?

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:

How many times does require read a JSON file?

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.

How to read a JSON file in Node JS?

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.

How to read JSON file in one line of code?

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:


2 Answers

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.

like image 53
robertklep Avatar answered Oct 09 '22 19:10

robertklep


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.

like image 30
Akshay Kumar Avatar answered Oct 09 '22 17:10

Akshay Kumar