我有这个模块
export default () => ({
environment: process.env.ENVIRONMENT,
port: process.env.PORT
database: {
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
username: 'postgres',
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
},
awsSqsDefaultQueueUrl: process.env.AWS_SQS_DEFAULT_QUEUE_URL,
sqsEndpoint: process.env.SQS_ENDPOINT,
})
我想读取它,并创建一个平面键/值对象,仅当值以process.env
开头时,该对象才会平面化其键,如下所示:
{
ENVIRONMENT: configuration().environment,
PORT: configuration().port,
DATABASE_HOST: configuration().database.host
DATABASE_PORT: configuration().database.port
...
}
database.username
不会出现在新对象键中,因为它的值不是以process.env
开头的。
我唯一能想到的方法是,在不计算键值之前读取键值,方法是将文件加载为字符串,然后使用regex解析它。但这感觉不对。
有更好的方法来实现这一点吗?
这里有一个想法:
const settings = () => ({
environment: process.env.ENVIRONMENT,
port: process.env.PORT,
database: {
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
username: 'postgres',
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
},
awsSqsDefaultQueueUrl: process.env.AWS_SQS_DEFAULT_QUEUE_URL,
sqsEndpoint: process.env.SQS_ENDPOINT,
});
function parseEnvSettings() {
// test values
process.env.ENVIRONMENT = "TEST";
const str = settings.toString();
const pattern = /process.env.[a-zA-Z0-9_]+/g;
// get your property names
const matches = [...str.match(pattern).values()];
// build your flat settings object
const parsedSettings = {};
matches.forEach(property => {
parsedSettings[property.substr(property.lastIndexOf(".") + 1)] = eval(property);
});
// here you go
console.log(parsedSettings);
}
parseEnvSettings();
产品:
{
ENVIRONMENT: 'TEST',
PORT: undefined,
DATABASE_HOST: undefined,
DATABASE_PORT: undefined,
DATABASE_PASSWORD: undefined,
DATABASE_NAME: undefined,
AWS_SQS_DEFAULT_QUEUE_URL: undefined,
SQS_ENDPOINT: undefined
}