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