EN
Node.js - application configuration in JSON file
6
points
In this short article, we would like to show how to store additional Node.js application configuration in JSON file.
The main concept of the presented solution is to:
- read and parse
config.json
at the application beggining, - exit the application when it is impossible to read config, printing error message.
Practical example
Example index.js
file:
const fs = require('fs');
const path = require('path');
let globalConfig;
try {
const filePath = path.resolve(__dirname, 'config.json');
const fileJson = fs.readFileSync(filePath, 'utf-8');
globalConfig = JSON.parse(fileJson);
} catch (ex) {
console.error(`Config file reading error. (${ex.message})`);
process.exit(1);
}
// Application source code here ...
// e.g.:
console.log(globalConfig.username);
console.log(globalConfig.password);
Example config.json
file:
{
"username": "john",
"password": "P@ssword"
}
Console:
john
P@ssword
Preview:
