How to generically update an existing environment variable to .env file?

I am using dotenv to load env variables and use in my mocha test. But based on a function that is generating a new token value for one of the existing environment var, I want to be able to generically update its value to .env file. Is it possible?

testSpec.js :

const webapi = require('../libs/webapi')

async function getVal() {
//to generate a new token using existing one
token = webapi.generate( process.env.BASE_URI, process.env.C_KEY, process.env.AUTH_TOKEN)
token.then(response => {
        obj = JSON.parse(response.body)
        authToken = obj.auth_token

.env :


From testSpec.js generate() generates a new token value that I’m parsing i.e; authToken ; that I want to generically update in the .env file for AUTH_TOKEN var in place of its previous value. Is it possible to write/update to .env for its updated value through some lib? I am new to nodejs and using npm packages, any help appreciated.

36 thoughts on “How to generically update an existing environment variable to .env file?”

  1. Here’s an approach that can perhaps address what you’re trying to do:

        const fs = require('fs');
        const envItems = ['BASE_URI', 'C_KEY', 'AUTH_TOKEN'];
        function updateEnv(items = [], eol = '\n'){
          const envContents = items
            .map(item => `${item}=${process.env[item]}`)
          fs.writeFileSync('.env', envContents);

    In the part where you set your auth_token, you’d update the environment variable and .env file:

    process.env.AUTH_TOKEN = obj.auth_token;

Leave a Comment