2013-10-28 41 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

相关问题