Search code examples
node.jscommand-line-interfacedotenv

Configuring process.env object with a Nodejs script


Is it possible to add an environment variable using a Nodejs CLI script to the process.env object and have it available in a javascript environment?

Something like this

node index.js --env --NEW_VARIABLE=1
// index.js

console.log('process.env["NEW_VARIABLE"]:', process.env["NEW_VARIABLE"]);
// logs 1

If it is, can it be done with strings, and how? One more thing, assuming all of this can be done...can it be done with a Jest script as well?


Solution

  • There's another property on the process object called "argv". It's an array of strings. You can push arguments into the argv array by added them as flags at the end of a CLI script.

    ex:

    node index.js -"new variable"
    
    // index.js
    
    console.log('process.argv:', process.argv);
    
    /*
    process.argv: [
          '/Users/user/.nvm/versions/node/v16.14.0/bin/node',
          '/Users/user/.nvm/versions/node/v16.14.0/bin/jest',
          '__tests__/api.test.js',
          '-new variable' // <- 
        ]
    */
    
    

    This will work with both node and jest scripts

    source: https://www.digitalocean.com/community/tutorials/nodejs-command-line-arguments-node-scripts