问题描述
我正在尝试从aws参数存储访问我的环境变量,但是我不确定如何在所有文件中访问它们而不将其设置为全局文件或将其存储在process.env中。 有没有更安全的方法呢?我想使用导出这些变量,但是由于导出过程在运行时和我的aws参数在此之后。 谢谢。
注意:-我没有在无服务器环境中可以直接通过变量名访问它们。
解决方法
环境变量是在单个应用程序内进行通信的一种非常糟糕的方法。它们通常用作在多个应用程序之间进行通信的一种解决方案。
在应用程序中存储和获取配置参数的通常方法是使用模块。是的,模块通常包含代码,但是没有什么可以阻止您创建仅存储数据的模块。确实,这是存储设置的相当标准的机制。
JSON文件
对于固定的配置值(例如配置文件),标准是仅使用json文件。例如:
config.json:
{
"port": 3000
}
然后,您可以在需要的地方仅需要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的限制性太强,因为您不能在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
的值。这使得节点模块的行为像单例。在上面的示例中,config
和main.js
中的some_module.js
变量指向同一个对象!我将重复一遍,因为它很重要:在上面的示例中,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模块,但上面的其他模块具有更多功能。