Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables in javascript

I'm trying to set some environment variables which can be picked up by my bash script.

order of execution:

version.js

module.exports.version = function () {
   process.env['APP_VERSION'] = `1.0.0`;
}

script.sh

run x 
run y
node -e "require('./version.js').version()"
echo "APP_VERSION=$APP_VERSION"

but echo output is

APP_VERSION=
like image 742
ir2pid Avatar asked Sep 18 '25 13:09

ir2pid


1 Answers

This is not possible. It's not an issue with node, it's just not possible period even any other language. If a child process could modify the environment variables of its parent that would be a huge security issue.

The only reason export works in the bash process itself is becuase you run those scripts in the bash process by "sourcing" them so it's modifying its own environment variables.

Example

#!/bin/sh
# test.sh
export FOOBAR=Testing
$ ./test.sh
echo $FOOBAR

prints nothing because test.js was run in its own process

$  source test.sh
echo $FOOBAR

prints 'Testing' because in this case test.sh was read and processed by the current bash process itself.

The best you could really do is export a shell script that the shell then executes

// example.js
const key = 'FOOBAR';
const value = `hello world: ${(new Date()).toString()}`;
console.log(`export "${key}"="${value}"`)
node example.js | source /dev/stdin 
echo $FOOBAR

But of course that output is specific to the shell you're running in meaning if you switch shells then what you need to output changes. It's also not a normal way to do this.

A more common way might be to output just the value from node

run x 
run y
$APP_VERSION=`node -e "console.log(require('./version.js').version())"`
echo "APP_VERSION=$APP_VERSION"