javascriptnode.jsnpmenvironment-variables

Node.JS: how do I set an environment variable in 1 file to be read all others?


I have a bunch of files that run various tests and return results to a log file.

I have helper functions that create and log file and add to it.

I want to dynamically name that log file, based off the time and date of when the script is run. To that end I need to store the file's name in a variable on the file that triggers all the tests (main.js) and make it available to the functions in my helper-function.js file.

I've been experimenting with setting a environmental variable on main.js but have had no success getting all the helper functions to read it.

Whilst it seems I can set it on main.js and have the createLogs() function use it, the subsequent updateLogs() function, which is exported (module.exports = {updateLogs}) to other files, cannot. I'm guessing the other files are simply not "aware" of the environment variable.

However, hard coding the environment variable in helper-functions.js works - both helper functions can see it and use it.

Does anyone know a way I can set process.env.LOGFILE with a dynamic value and make it available to all helper functions? (note: due to security restrictions I cannot use 3rd party packages to achieve this). `

My files are as such:

//main.js
const d = new Date();
const logName = "fooBar";
process.env.LOGFILE = logName + "-" + d.getDay() + "-" + d.getMonth() + "-" + d.getFullYear()  +  ".json";
createLogs(logName);

// Running tests on other files...

helper-functions.js

//If I uncomment the below it works, but file name is hard coded.
//process.env.LOGFILE = "customLogs.json";
    
//Create log file when scripts are first run
const createLogs = (logName) => {
    exec('git branch --show-current', (err, stdout, stderr) => {
        if (err) {
            console.log("Error getting git branch:" + stderr);
        }

        const startTime = ((Date()).toLocaleString()).split('GMT')[0];
        const branchName = stdout ? stdout.replace(/(\r\n|\n|\r)/gm,"") : "no-branch";

        let repObjString = `{"details":{"name": "${logName}","time": "${startTime}","branch": "${branchName}"},"report":{}}`;

        const logFileName = `logs/${process.env.LOGFILE}`; //<== THIS WORKS
        if (!fs.existsSync(logFileName)) {
            console.log("Log doesnt exist. Making one...");
            fs.writeFile(logFileName, repObjString, function (err) {
                if (err) throw err;
                console.log('Creating file!');
            });
        }
    });
}

// Update logs
const updateLogs = (logObj) => {
    const logName = `logs/${process.env.LOGFILE}`; //<== THIS DOES NOT WORK

    fs.readFile(logName, 'utf8', function (err, logData) {
        if (err) throw err;
        Object.assign(logData["report"], logObj);
        fs.writeFile (logName, logData, function(err) {
            if (err) throw err;
            console.log('Log updated');
        });
    });
}

Solution

  • // node createEnvFile.js
    import { writeFileSync } from "node:fs";
    writeFileSync(".env", "LOGFILE=fooBar");
    
    node --env-file=.env main.js
    
    const logName = process.env.LOGFILE ...