Isa*_*odo 6 javascript node.js
我正在编写一个普通的 .env 文件,如下所示:
VAR1=VAL1
VAR2=VAL2
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一些模块可以在 NodeJS 中使用来产生一些效果,例如:
somefunction(envfile.VAR1) = VAL3
Run Code Online (Sandbox Code Playgroud)
结果.env文件将是
VAR1=VAL3
VAR2=VAL2
Run Code Online (Sandbox Code Playgroud)
即在其他变量不变的情况下,只更新选定的变量。
Mar*_*arc 21
您可以使用fs,os模块和一些基本的数组/字符串操作。
const fs = require("fs");
const os = require("os");
function setEnvValue(key, value) {
// read file from hdd & split if from a linebreak to a array
const ENV_VARS = fs.readFileSync("./.env", "utf8").split(os.EOL);
// find the env we want based on the key
const target = ENV_VARS.indexOf(ENV_VARS.find((line) => {
return line.match(new RegExp(key));
}));
// replace the key/value with the new value
ENV_VARS.splice(target, 1, `${key}=${value}`);
// write everything back to the file system
fs.writeFileSync("./.env", ENV_VARS.join(os.EOL));
}
setEnvValue("VAR1", "ENV_1_VAL");
Run Code Online (Sandbox Code Playgroud)
.env
VAR1=VAL1
VAR2=VAL2
VAR3=VAL3
Run Code Online (Sandbox Code Playgroud)
执行完毕后,VAR1将ENV_1_VAL
没有外部模块就没有魔法;)
我认为公认的解决方案足以满足大多数用例,但我个人在使用时遇到了一些问题:
ENV_VARENV_VAR_FOO.env,它将替换文件的最后一行.env。就我而言,我想做一个更新插入,而不是仅仅更新现有的环境变量。我从马克的答案中修改了一些内容来解决上述问题:
function setEnvValue(key, value) {
// read file from hdd & split if from a linebreak to a array
const ENV_VARS = fs.readFileSync(".env", "utf8").split(os.EOL);
// find the env we want based on the key
const target = ENV_VARS.indexOf(ENV_VARS.find((line) => {
// (?<!#\s*) Negative lookbehind to avoid matching comments (lines that starts with #).
// There is a double slash in the RegExp constructor to escape it.
// (?==) Positive lookahead to check if there is an equal sign right after the key.
// This is to prevent matching keys prefixed with the key of the env var to update.
const keyValRegex = new RegExp(`(?<!#\\s*)${key}(?==)`);
return line.match(keyValRegex);
}));
// if key-value pair exists in the .env file,
if (target !== -1) {
// replace the key/value with the new value
ENV_VARS.splice(target, 1, `${key}=${value}`);
} else {
// if it doesn't exist, add it instead
ENV_VARS.push(`${key}=${value}`);
}
// write everything back to the file system
fs.writeFileSync(".env", ENV_VARS.join(os.EOL));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8174 次 |
| 最近记录: |