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 ?
Don't Use JSON as a Configuration File Format.
json. nconf wrapper that simplifies work with environment specific configuration files.
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.
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.
You should accept both.
JavaScript configuration files have many advantages:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With