首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >nodejs配置模块乐观主义者还是nconf?

nodejs配置模块乐观主义者还是nconf?
EN

Stack Overflow用户
提问于 2013-06-01 03:11:31
回答 2查看 9.6K关注 0票数 6

我刚刚开始用NodeJS编写我的第一个应用程序,我必须说学习如何使用是一种愉快的事情:)

我已经到了在启动服务器之前进行一些配置的阶段,我想从config.json文件中加载配置。

到目前为止,我已经找到了几种方法,要么请求json文件,离线节点需要解析它,使用config.js文件并导出我配置,使用nconf,这似乎很容易使用,或者我看到的最后一种方法是使用optimist,我认为它比ncond更好。虽然我开始认为后者,乐观主义者,只能用于解析来自节点cli的参数。

所以我在这里问,我可以使用node optimist从文件中获取配置吗?如果不能,我应该使用nconf吗?或者,也许有一些我不知道的更好、更轻量级的东西?(在这一点上,我的选择非常模糊,因为我不确定是否希望在某个时候从cli中解析任何配置)。

EN

回答 2

Stack Overflow用户

发布于 2014-04-30 09:02:55

我使用dotenv。它很简单,就像:

代码语言:javascript
复制
var dotenv = require('dotenv');
dotenv.load();

然后,您只需使用您的配置设置创建一个.env文件。

代码语言:javascript
复制
S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

免责声明:我是创建者,没有发现config.json文件方法在生产环境中有用。我更喜欢从我的环境变量获取配置。

票数 4
EN

Stack Overflow用户

发布于 2021-02-16 17:10:10

6年后,答案应该是:使用Nconf。太棒了。

代码语言:javascript
复制
//
// 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();

则在任何其他文件中

代码语言:javascript
复制
const options = require('./options');

console.log(`PORT: ${options.port}`);

现在,您可以像这样运行您的项目:

代码语言:javascript
复制
$ 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

如果你忘记了你有什么选择

代码语言:javascript
复制
$ yarn start --help
# prints out all the options
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16864250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档