node.js, include json file
config.json
[code language=”javascript”]
{
"database" : {
"host" : "localhost",
"user" : "admin",
"password": "123456789",
"dbname": "finance-db"
},
"inputs" : {
"infile" : "./input-file.csv",
"outfile" : "./output-file.csv"
}
}
[/code]
3 ways to include the config.json. First one, require with file path.
[code language=”javascript”]
var parsedJson = require(‘./config.json’);
[/code]
Second one, require with the file path but without the file extension.
[code language=”javascript”]
var parsedJson = require(‘./config’);
[/code]
Third one, read the file and then parse the file content into json object.
[code language=”javascript”]
var fs = require("fs");
var parsedJson = (JSON.parse(fs.readFileSync("./config.json", "utf8")));
[/code]
All together:
[code language=”javascript”]
//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
[/code]
Search within Codexpedia

Search the entire web
