Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS vs JSON for config in Node js [closed]

What should I use for configuration ?

Some module like KrakenJS highly supports configuration through JSON and the blog https://blog.risingstack.com/node-js-best-practices-part-2/ say JS should be preferred over JSON.

Can you tell me how they differ and what's the best way to manage them ?

like image 628
Deendayal Garg Avatar asked Apr 26 '16 11:04

Deendayal Garg


People also ask

Is JSON good for config file?

Don't Use JSON as a Configuration File Format.

What is config JSON in node JS?

json. nconf wrapper that simplifies work with environment specific configuration files.

What is the difference between node JS and JSON?

With node. js as backend, the developer can maintain a single codebase for an entire application in javaScript. JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.

Why we use config in node JS?

Node-config allows you to create configuration files in your Node application for different deployment environments. With it, you can define a default configuration file that you intend to repeat across environments, then extend the default config to other environments, such as development, staging, etc.


1 Answers

You should accept both.

JavaScript configuration files have many advantages:

  1. programmable of course, which allows for interesting extensions and for generated parts
  2. lighter and less awkward to type (less quotes, trailing commas, etc.)
  3. lets you have comments (a big limitation of JSON, here's why they're needed)
  4. more value types (NaN & infinites, regular expressions for example)

In this case the JS file exports a plain JS object, similar to what you would have had as a result of a parsed JSON file.

JSON is more socially accepted, because JS isn't often thought as a configuration format. Letting people use JSON will prevent a "JS is for logic" sterile debate and there's no problem if people are happy with it.

Accepting both formats:

Here's how reading the JS/JSON configuration can be done:

try {
    config = require('./config.js');
} catch(err) {
    if (err.code==='MODULE_NOT_FOUND') {
        config = require('./config.json');
    } else {
        console.error('config.js loading failed');
        throw err;
    }
}

In any case, the JSON configuration file can be turned to a JS one by just prefixing it with

module.exports =

so nobody's locked in that format.

like image 152
Denys Séguret Avatar answered Oct 12 '22 13:10

Denys Séguret