环境变量是在单个应用程序中进行通信的一种非常糟糕的方式。它们通常用作在多个应用程序之间进行通信的一种解决方案。
在您的应用中存储和获取配置参数的常规方法是使用模块。是的,模块通常包含代码,但没有什么能阻止您创建仅存储数据的模块。事实上,这是一种相当标准的设置存储机制。
JSON 文件
对于配置文件等固定配置值,标准是只使用 json 文件。例如:
config.json:
{
"port": 3000
}
然后你可以在任何你需要的地方 require json 文件:
main.js:
config = require('./config'); // node will automatically search for
// config.js or config.json
app.listen(config.port);
some_module.js:
config = require('../../config');
console.log('we connected via port', config.port);
JS 文件
有些人觉得 JSON 限制太多,因为不能将 cmets 放在 JSON 文件中。大多数人通常会从常规的 js 模块中导出对象:
lib/config.js:
let config = {
port: 3000, // port to listen to, LOOK! COMMENTS!!
messagePrefix: 'Hello ', // also, don't need to quote property names
// also, can use single quotes for strings
// also, dangling quotes are supported
}
module.exports = config
main.js:
const config = require('./lib/config');
app.listen(config.port);
some_module.js:
const config = require('./lib/config');
console.log(config.messagePrefix + 'World'); //Hello World
要了解require 如何工作的一点是,它将缓存模块生成的module.exports 的值。这使得节点模块表现得像单例。在上面的例子中,main.js 和some_module.js 中的config 变量指向同一个对象!我将再次重复这一点,因为它很重要:在上面的示例中,node.js 创建了只有一个配置对象。这意味着您可以使用像config.js 文件这样的纯数据模块在代码中的模块之间进行通信。例如,您可以这样做:
main.js:
const config = require('./lib/config');
config.messagePrefix = 'Goodbye ';
app.listen(config.port);
some_module.js:
const config = require('./lib/config');
console.log(config.messagePrefix + 'World'); //Goodbye World
从其他地方读取配置的 JS 文件
因为我们使用普通模块与我们的其余代码通信配置数据,所以我们可以运行我们想要生成配置的任何算法:
config.js:
let config = {};
// Try to load default config:
try {
let rawdata = fs.readFileSync('./default-config.json');
config = JSON.parse(rawdata);
}
catch (err) {
// cannot load default config, just skip it
}
// Try to load user-specific config:
try {
// Read some configs from a file:
let rawdata = fs.readFileSync('./config.json');
let userconfig = JSON.parse(rawdata);
// override default configs:
for (prop in userconfig) {
config[prop] = userconfig[prop];
}
}
catch (err) {
// cannot load user config, just skip it
}
// Override default config and user config if environment variable is set:
if (process.env.PORT) {
config.port = process.env.PORT;
}
module.exports = config;
如上例所示。您可以使用任何逻辑来构造配置数据。如果任何配置数据来自异步源(例如数据库),您将需要更有创意,但您可以将整个模块包装在一个 Promise 中并等待配置。
一般配置应保存在文件中。不是环境变量。环境变量应该存储有关环境的信息,例如 C 编译器的路径在哪里,或者您的 Web 浏览器在哪里,或者这台计算机配置为默认使用什么语言。进程端口号之类的东西不应该存储在环境变量中,尽管传统上(我指的是从 1960 年代发展到今天的 Unix 传统)传统上可以接受使用环境变量来覆盖配置以帮助调试。
根据您使用的操作系统,人们传统上存储配置文件的位置有很多:Unix 上的 /etc 目录,Windows 上的 Application Data,现代 unix 桌面上的 ~/.config 目录等。
有几个 npm 模块可以帮助您组织配置文件。根据您的需要,您可能会发现 rc 或 config 或 configstore 有用。我个人想推广我自己的config-default-cjson 模块,但上面的其他模块有更多功能。