5

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 :(

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

@Zeck You can create a conf.js, that does: var env = process.env.NODE_ENV || 'development'; module.exports = require("./config")[env]; Then require('conf') wherever you're using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.