I see multiple ways to create config files in Node.js. One uses module.exports in js file, one just use plain json object.
// config1.js module.exports = { config_1: "value 1", config_2: "value 2" }
// config2.json { "config_1": "value 1", "config_2": "value 2" }
Is there any advantages of using module.exports in config file? What are the differences?
When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way. 2.
Module exports are the instruction that tells Node. js which bits of code (functions, objects, strings, etc.) to “export” from a given file so other files are allowed to access the exported code.
If you prefer to use JavaScript, you can add it to your server file before calling the configuration library, as shown below: js const express = require('express'); process. env. NODE_CONFIG = '{"server": {"host":"localhost", "port":"3030"}}'; const config = require('config');
Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.
So I always start with a commonjs module for the convenience, but keep any logic in there simple. If your config.js has bugs and needs tests, it's probably too complicated. KISS. If I know for a fact other things are going to want poke around in my config, I'll use a JSON file.
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