Languages
[Edit]
EN

Node.js - application configuration in JSON file

6 points
Created by:
Evania
584

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:

  1. read and parse config.json at the application beggining,
  2. 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:

Node.js application configuration in JSON file.
Node.js application configuration in JSON file.

See also

  1. Node.js - read JSON files 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join