JS vs JSON for configuration in Node js

What should I use for configuration?

Some modules, such as KrakenJS, highly support configuration through JSON and the blog https://blog.risingstack.com/node-js-best-practices-part-2/ , where JS should be preferred over JSON.

Can you tell me how they differ and how best to manage them?

+6
source share
1 answer

You must accept both.

JavaScript configuration files have many advantages:

  1. programmable, of course, which takes into account interesting extensions for the generated parts
  2. lighter (e.g. fewer quotes)
  3. allows you to have comments (a big JSON limitation, which is why they are needed )
  4. other types of values ​​( NaN and infinite, for example, regular expressions)

In this case, the JS file exports a simple JS object, similar to the one you would have from parsing the JSON file.

JSON is more socially acceptable because JS is often not considered as a configuration format. Allowing people to use JSON will prevent the "JS is for logic" fruitless debate, and there will be no problem if people are happy with it.

We accept both formats:

Here's how to read the JS / JSON configuration:

 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 into a JS file by simply adding the prefix to it

 module.exports = 

so no one is locked in this format.

+10
source

Source: https://habr.com/ru/post/1247933/


All Articles