Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share configuration variables in Nodejs application

I'm new to JavaScript/Nodejs. How can I share my configuration across the Nodejs application. For example: I have a config/config.coffee

path = require("path")

module.exports = {
  development:
    db: 'mongodb://localhost/hello'
    root: rootPath = path.normalize(__dirname + '/..')
}

I included config.coffee in my app.coffee.

express = require("express")

# Load configurations
env = process.env.NODE_ENV || 'development'
config = require("./config/config")[env]

require('./config/boot')

app = express()

Now I want to include config variable into my config/boot.coffee. How can I do it? I don't want to re-include config/config.coffee into config/boot.coffee. Here is the my config/boot.coffee file:

env = process.env.NODE_ENV || 'development'
config = require("./config")[env]
fs = require("fs")
mongo = require("mongoose")

# Bootstrap db connections
mongo.connect config.db

# Bootstrap models
models_path = config.root+"/app/models"
fs.readdirSync(models_path).forEach( (file)->
  require(models_path + '/' + file) if ~file.indexOf('.coffee')
)

# Bootstrap services
services_path = config.root+"/app/services"
fs.readdirSync(services_path).forEach( (file)->
  require(models_path + '/' + file) if ~file.indexOf('_service.coffee')
)

Sorry for bad English :(

like image 329
Zeck Avatar asked Oct 03 '22 14:10

Zeck


2 Answers

You might want to check out nconf, which helps you keep a kind of "waterfall" approach to application configuration, which allows you to mix your configuration from different sources very transparently.

You can see nconf in action in this project I wrote, unbox, which is basically boilerplate I use for applications I write on Node. You can check out how configuration is loaded here.

You could use something like grunt-pemcrypt for increased security by checking in the secure, encrypted file, and saving the encryption key somewhere safe.

12factor also has a nice approach to application configuration you might want to look into.

like image 52
bevacqua Avatar answered Oct 13 '22 10:10

bevacqua


I believe NodeJS caches your require's, so calling require('config') again won't cause any performance degradation.

http://nodejs.org/api/globals.html#globals_require

like image 37
lxe Avatar answered Oct 13 '22 10:10

lxe