如何在运行时使用node-config覆盖configuration值?
我想在testing时重写一些值,特别是将http服务的重试设置为1(立即失败,不重试)。 我们的项目使用node-config
。 根据文档我可以用NODE_CONFIG
envvariables覆盖:
node myapp.js --NODE_CONFIG='{"Customer":{"dbConfig":{"host":"customerdb.prod"}}}'
那么我宁愿在我的testing中这样做,但不是所有的testing。 代码说你可以通过设置ALLOW_CONFIG_MUTATIONS
来允许configurationALLOW_CONFIG_MUTATIONS
。
process.env.ALLOW_CONFIG_MUTATIONS = "true"; const importFresh = require('import-fresh'); importFresh("config"); process.env.NODE_CONFIG = JSON.stringify({httpServices:{integration:{enrich: {retryInterval: 1, retries: 1}}}}); expect(process.env.NODE_CONFIG, 'NODE_CONFIG not set').to.exist(); expect(process.env.NODE_CONFIG, 'NODE_CONFIG not set').to.match(/retryInterval/); expect(process.env.ALLOW_CONFIG_MUTATIONS, 'ALLOW_CONFIG_MUTATIONS not set').to.equal("true"); const testConfig = require("config"); console.dir(testConfig.get("httpServices.integration.enrich")); expect(testConfig.get("httpServices.integration.enrich.retryInterval"), 'config value not set to 1').to.equal(1);
结果:
{ url: 'https://internal-**********', retryInterval: 5000, retries: 5 } `Error: config value not set to 1: Expected 5000 to equal specified value: 1`
我如何得到这个覆盖工作?
(期望来自Hapi.js代码库)
我是node-config
的维护者之一。 你的bug是你用过的第二次require
再次使用importFresh
时候。
你首次使用“importFresh()”与require()
不同,因为它是require()
的第一个用法。
在设置了一些variables之后,你可以调用require()
,它将返回已经生成和caching的config
文件的副本,而忽略环境variables集的影响。
您只需要在当前使用require()
地方使用importFresh()
一次。 这将导致configuration对象的“新鲜”副本被返回,如您所料。
在configuration文件夹中创build一个development.json,production.json和test.json会更好。node-config将使用它来configuration你的应用程序。 你只是networking设置你的NODE_ENV使用特定的文件。 希望能帮助到你 :)