[英]How to save changes in .env file in 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';
.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
我用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!");
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.