node.js, include json file

config.json

{
	"database" : {
		"host" : "localhost",
		"user" : "admin",
		"password": "123456789",
		"dbname": "finance-db"
	},
	"inputs" : {
		"infile" : "./input-file.csv",
		"outfile" : "./output-file.csv"
	}
}

3 ways to include the config.json. First one, require with file path.

var parsedJson = require('./config.json');

Second one, require with the file path but without the file extension.

var parsedJson = require('./config');

Third one, read the file and then parse the file content into json object.

var fs = require("fs");
var parsedJson = (JSON.parse(fs.readFileSync("./config.json", "utf8")));

All together:

//var parsedJson = require('./config.json');
//var parsedJson = require('./config');
var fs = require("fs");
var parsedJson = (JSON.parse(fs.readFileSync("./config.json", "utf8")));

console.log(parsedJson);
console.log(parsedJson.database.host);		//localhost
console.log(parsedJson.database.user);		//admin
console.log(parsedJson.database.password);	//123456789
console.log(parsedJson.database.dbname);	//finance-db
console.log(parsedJson.inputs.infile);		//./input-file.csv
console.log(parsedJson.inputs.outfile);		//./output-file.csv

Search within Codexpedia

Custom Search

Search the entire web

Custom Search