我应该使用全局NodeJS来使配置属性对我的应用程序可用吗? [英] Should I use a NodeJS global to make config properties available to my application?
问题描述
我的问题相对简单:
在NodeJS中,您可以使用
In NodeJS you have the ability to set globals using
GLOBAL.myConfigObject = {...}
我对开发者社区的问题是这是否是最佳实践.如果没有,那么将配置变量(例如api-url或Port或ip地址)中继到整个应用程序的一种更好的方法.
My question for the developer community is whether or not this is best practice. If not, what would be a better way to relay config variables (such as api-url or Port or ip address) to the entire application.
推荐答案
不是为配置设置全局变量,而是为要在其中启动的环境使用全局变量.设置一个包含每个环境的config目录:
Instead of setting a global for the config, use a global for the environment you're launching in. Setup a config directory that has each of your environments:
config/local.js
module.exports = {
port: 3000,
ipAddress: "127.0.0.1"
}
config/production.js
module.exports = {
port: 443,
ipAddress: "8.8.8.8"
}
在启动服务器的主文件中:
in your main file where you spin up your server:
server.js
var config = require("./config/" + process.env.NODE_ENV)
// use your config however you need it
从命令行启动服务器,然后可以执行以下操作:
spinning up your server from the command line, you can then do:
NODE_ENV =本地节点server.js
这样,您只有一个全局变量指示您的环境,但是您可以使用该环境所需的任何配置变量.
This way, you have a single global variable indicating your environment, but you can use whatever configuration variables you need for that environment.
这篇关于我应该使用全局NodeJS来使配置属性对我的应用程序可用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!