a blog for those who code

Tuesday 7 June 2016

Load JSON files directly using require() in Node.js

In this post we will be discussing about loading JSON files directly using require() rather than using file system in Node.js. In Node.js you can use File System module for file I/O operations which is provided by simple wrappers around standard POSIX functions.

How File System in Node.js Works


Now if I have a .json configuration file and I need to get the values of the configuration in my application as a novice node.js developer , I will read the .json file using file system module as shown below :

var fs = require('fs');
var configs = fs.readFileSync('./config.json');
console.log(configs);

Using this approach you will not directly get the key using configs.keyname because fs.readFileSync just reads the data from the file but it doesn't parse it. To parse the data you need an additional step and that is as shown below :

var fs = require('fs');
var configWithoutParsing = fs.readFileSync('./config.json');
console.log(configWithoutParsing);
var consfigWithParsing = JSON.parse(configWithoutParsing);
console.log(consfigWithParsing);

The output of both the approach is shown below :


Use require() for reading .JSON files


Now coming back to our main topic to use require() for reading .json files. The require() function in Node.js can read both .js and .json files. If a file ends with .js, the file is parsed and interpreted as a JavaScript file whereas if a file ends with .json, the file is parsed and interpreted as a JSON text file.

For example have a look at the below code :

var config = require('./config.json');
console.log(config);
console.log('Value of Value1 is ' + config.value1);

will give an output as


So as you can see in the above code require() not only reads the data form the .json file but also parse it.

One thing to note that file extension is not mandatory because Node.js will look for a .js file first and if it is not found it will look for .json file. This means we can start off using a completely static .json file and need not have to worry if we need to change it later to a .js file.

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

1 comment:

  1. Great post. I was checking continuously this blog and I am
    impressed! Very useful information specifically the ultimate part :) I
    handle such information a lot. I used to be seeking this
    certain info for a very lengthy time. Thanks and good luck.

    ReplyDelete