如何将.env文件中的更改保存在node.js中



我使用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文件。我阅读了其他解决方案,并编写了两个函数getEnvValuesetEnvValue以简化读/写操作。

要使用getEnvValue,.env文件的格式应如下所示(即=符号周围没有空格(:

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')

.env文件

VAR1=var1Value
VAR_2=var2Value

index.js文件

const fs = require('fs') 
const envfile = require('envfile')
const sourcePath = '.env'
console.log(envfile.parseFileSync(sourcePath))
let parsedFile = envfile.parseFileSync(sourcePath);
parsedFile.NEW_VAR = 'newVariableValue'
fs.writeFileSync('./.env', envfile.stringifySync(parsedFile)) 
console.log(envfile.stringifySync(parsedFile))

最终.env文件安装所需的模块并执行index.js文件

VAR1=var1Value
VAR_2=var2Value
NEW_VAR=newVariableValue

不要将数据保存到.env文件中

什么是.env文件

env代表环境变量。环境变量是基于shell的键值对,为正在运行的应用程序提供配置。

.env文件旨在提供在开发过程中设置这些环境变量的简单机制(通常是因为开发人员机器不断重启,打开了多个shell,开发人员必须在需要不同环境变量的项目之间切换(。在生产中,这些参数通常由实际的环境变量传递(在云配置中,这些变量通常比基于文件的解决方案更容易管理,并防止任何机密保存在磁盘上(

为什么不能修改环境变量

环境变量可以在命令行中修改,但一旦启动正在运行的进程,它就不会影响父进程的环境变量。如果程序退出并重新启动,所做的更改将丢失。

为什么不能修改.env文件

如果在.env文件中设置了一个值,则只有在不存在同名环境变量时才会使用该值。如果是,则不会加载.env文件中该变量的值。

此外,在重新启动应用程序之前,读取process.env时,写入.env文件的任何更改都不会反映在应用程序中。

请改用配置文件

配置文件只是一个包含配置的常规文件。它就像一个.env文件,但它并不表示环境变量。更换它是安全的,在生产中使用也是安全的。

更新:2022年3月-Typescript示例

请参阅@Codebling关于为什么NOT应该这样做的帖子,但您可能将其用作某种形式的测试。不管下面的用例是什么。

使用库envfile

安装包:npm i envfile

OR作为开发依赖项:npm i envfile --save-dev

import { resolve } from 'path';
import { readFile, writeFileSync } from 'fs';
import * as envfile from 'envfile';
export const writeEnvToFile = (
envVariables: { key: string; value: any }[],
): void => {
// get `.env` from path of current directory
const path = resolve(__dirname, '../../.env');
readFile(path, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
const parsedFile = envfile.parse(data);
envVariables.forEach((envVar: { key: string; value: any }) => {
if (envVar.key && envVar.value) {
parsedFile[envVar.key] = envVar.value;
}
});
writeFileSync(path, envfile.stringify(parsedFile));
// NB: You should now be able to see your .env with the new values,
// also note that any comments or newlines will be stripped from 
// your .env after the writeFileSync, but all your pre-existing
// vars should still appear the .env.
console.log('Updated .env: ', parsedFile);
});
};

示例用法

writeEnvToFile([
{
key: 'YOUR_NEW_ENV_VAR',
value: 'SOME_VALUE',
},
{
key: 'FOO',
value: 'BAR',
},
{
key: 'TIME_STAMP',
value: 1647934964293,
},
]);

.env写入前

# Some comments about API KEY
API_KEY=xxxabc

.env写入后

API_KEY=xxxabc
YOUR_NEW_ENV_VAR=SOME_VALUE
FOO= BAR
TIME_STAMP=1647934964293

我解决了envfile模块的问题:

const envfile = require('envfile');
const sourcePath = '../../.env';
let sourceObject = {};
// Parse an envfile path
// async
envfile.parseFile(sourcePath, function (err, obj) {
//console.log(err, obj)
sourceObject = obj;
sourceObject.DB_HOST = '192.168.1.62';
envfile.stringify(sourceObject, function (err, str) {
console.log( str);
fs.writeFile(sourcePath, str, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
});

最新更新