Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module.exports vs plain json for config files

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?

like image 821
Nam Nguyen Avatar asked Aug 27 '13 22:08

Nam Nguyen


People also ask

What's the difference between module exports and exports?

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.

What is the purpose of module exports explain with example?

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.

How create config file in JavaScript?

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');

What module exports do?

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.


1 Answers

javascript CommonJS Module

  • comments
  • conditionals
  • loops and such to populate defaults
  • code to change config based on NODE_ENV or similar
  • code to look for external files for SSL keys, API credentials, etc
  • easier to have fallbacks and defaults

JSON file

  • easy to parse and update with external tools
  • compatible with pretty much every programming language out there
  • pure data that can be loaded without being executed
  • easy to pretty print
  • JSON could start as the basis and all the code items described above about CommonJS module could live in a config.js module that reads config.json as it's starting point

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.

like image 174
Peter Lyons Avatar answered Sep 20 '22 17:09

Peter Lyons