如何在node.js中的.env文件中保存更改 [英] How to save changes in .env file in node.js

查看:75
本文介绍了如何在node.js中的.env文件中保存更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 dotenv 读取环境变量.像这样:

I use dotenv for read environment variable. like this:

let dotenv = require('dotenv').config({ path: '../../.env' });
console.log(process.env.DB_HOST);

现在,我想将更改保存在 .env 文件中.我找不到在 .env 文件中保存变量的任何方法.我该怎么办?

Now I wanna to save changes in .env file. I can't find any way to save variable in .env file. What should I do?

process.env.DB_HOST = '192.168.1.62';

推荐答案

.env文件

VAR1=var1Value
VAR_2=var2Value

index.js文件

index.js file

    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文件

final .env file install required modules and execute index.js file

VAR1=var1Value
VAR_2=var2Value
NEW_VAR=newVariableValue

这篇关于如何在node.js中的.env文件中保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆