我刚刚开始用NodeJS编写我的第一个应用程序,我必须说学习如何使用是一种愉快的事情:)
我已经到了在启动服务器之前进行一些配置的阶段,我想从config.json文件中加载配置。
到目前为止,我已经找到了几种方法,要么请求json文件,离线节点需要解析它,使用config.js文件并导出我配置,使用nconf,这似乎很容易使用,或者我看到的最后一种方法是使用optimist,我认为它比ncond更好。虽然我开始认为后者,乐观主义者,只能用于解析来自节点cli的参数。
所以我在这里问,我可以使用node optimist从文件中获取配置吗?如果不能,我应该使用nconf吗?或者,也许有一些我不知道的更好、更轻量级的东西?(在这一点上,我的选择非常模糊,因为我不确定是否希望在某个时候从cli中解析任何配置)。
发布于 2014-04-30 09:02:55
我使用dotenv。它很简单,就像:
var dotenv = require('dotenv');
dotenv.load();然后,您只需使用您的配置设置创建一个.env文件。
S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE免责声明:我是创建者,没有发现config.json文件方法在生产环境中有用。我更喜欢从我的环境变量获取配置。
发布于 2021-02-16 17:10:10
6年后,答案应该是:使用Nconf。太棒了。
//
// yourrepo/src/options.js
//
const nconf = require('nconf');
// the order is important
// from top to bottom, a value is
// only stored if it isn't found
// in the preceding store.
// env values win all the time
// but only if the are prefixed with our appname ;)
nconf.env({
separator: '__',
match: /^YOURAPPNAME__/,
lowerCase: true,
parseValues: true,
transform(obj) {
obj.key.replace(/^YOURAPPNAME__/, '');
return obj;
},
});
// if it's not in env but it's here in argv, then it wins
// note this is just passed through to [yargs](https://github.com/yargs/yargs)
nconf.argv({
port: {
type: 'number'
},
})
// if you have a file somewhere up the tree called .yourappnamerc
// and it has the json key of port... then it wins over the default below.
nconf.file({
file: '.yourappnamerc'
search: true
})
// still not found, then we use the default.
nconf.defaults({
port: 3000
})
module.exports = nconf.get();则在任何其他文件中
const options = require('./options');
console.log(`PORT: ${options.port}`);现在,您可以像这样运行您的项目:
$ yarn start
# prints PORT: 3000
$ YOURAPPNAME__PORT=1337 yarn start
# prints PORT: 1337
$ yarn start --port=8000
# prints PORT: 8000
$ echo '{ "port": 10000 }' > .yourappnamerc
$ yarn start
# prints PORT: 10000如果你忘记了你有什么选择
$ yarn start --help
# prints out all the optionshttps://stackoverflow.com/questions/16864250
复制相似问题