2013-10-28 50 views
4

我是新來的JavaScript /的NodeJS。我如何通過Nodejs應用程序共享我的配置。例如:我有一個config/config.coffee如何共享配置變量在應用程序的NodeJS

path = require("path") 

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

我包括在我app.coffeeconfig.coffee

express = require("express") 

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

require('./config/boot') 

app = express() 

現在我想包括config可變進我config/boot.coffee。我該怎麼做?我不想將config/config.coffee重新包含到config/boot.coffee中。這裏是我的config/boot.coffee文件:

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

對不起,我英文不好:(

回答

2

你可能想看看nconf,它可以幫助你保持一種「瀑布式」的方式來應用配置,它允許你混合你的c非常透明地從不同來源進行配置。

你可以看到nconf中的行動在這個項目中我寫的,unbox,這基本上是樣板我用我寫在節點的應用程序。你可以看看如何加載配置here

您可以通過在安全,加密的文件檢查,並保存加密密鑰安全的地方使用類似grunt-pemcrypt以提高安全性。

12factor也有一個很好的方法來應用配置你可能想看看。

+1

哇,這是真棒,我書籤您的博客:) – Zeck

2

相信緩存的NodeJS您require的,所以再次調用require('config')不會造成任何性能下降

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

+1

感謝您的答覆。但我想要更多的DRY代碼。 – Zeck

+1

@Zeck你可以創建一個conf.js,這樣做:'var env = process.env.NODE_ENV || 「發展」; module.exports = require(「./ config」)[env];'然後'require('conf')'無論你在哪裏使用它。 – lxe

+0

謝謝你好主意:) – Zeck

相關問題