I use dotenv
用于读取环境变量。像这样:
let dotenv = require('dotenv').config({ path: '../../.env' });
console.log(process.env.DB_HOST);
现在我想保存更改.env
文件。我找不到任何方法来保存变量.env
文件。我应该怎么办?
process.env.DB_HOST = '192.168.1.62';
更新日期:2021 年 8 月
无外部依赖
我一直在寻找类似的解决方案来读取和写入键/值到 .env 文件。我阅读了其他解决方案并编写了两个函数getEnvValue
and setEnvValue
以简化读/写操作。
To use getEnvValue
,.env 文件的格式应如下所示(即周围没有空格=
sign):
KEY_1="value 1"
KEY_2="value 2"
const fs = require("fs");
const os = require("os");
const path = require("path");
const envFilePath = path.resolve(__dirname, ".env");
// read .env file & convert to array
const readEnvVars = () => fs.readFileSync(envFilePath, "utf-8").split(os.EOL);
/**
* Finds the key in .env files and returns the corresponding value
*
* @param {string} key Key to find
* @returns {string|null} Value of the key
*/
const getEnvValue = (key) => {
// find the line that contains the key (exact match)
const matchedLine = readEnvVars().find((line) => line.split("=")[0] === key);
// split the line (delimiter is '=') and return the item at index 2
return matchedLine !== undefined ? matchedLine.split("=")[1] : null;
};
/**
* Updates value for existing key or creates a new key=value line
*
* This function is a modified version of https://stackoverflow.com/a/65001580/3153583
*
* @param {string} key Key to update/insert
* @param {string} value Value to update/insert
*/
const setEnvValue = (key, value) => {
const envVars = readEnvVars();
const targetLine = envVars.find((line) => line.split("=")[0] === key);
if (targetLine !== undefined) {
// update existing line
const targetLineIndex = envVars.indexOf(targetLine);
// replace the key/value with the new value
envVars.splice(targetLineIndex, 1, `${key}="${value}"`);
} else {
// create new key value
envVars.push(`${key}="${value}"`);
}
// write everything back to the file system
fs.writeFileSync(envFilePath, envVars.join(os.EOL));
};
// examples
console.log(getEnvValue('KEY_1'));
setEnvValue('KEY_1', 'value 1')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)