ir2pid
ir2pid

Reputation: 6166

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=

Upvotes: 4

Views: 4448

Answers (3)

user128511
user128511

Reputation:

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"

Upvotes: 4

forkdbloke
forkdbloke

Reputation: 1565

Make use of Dotenv, where you can maintain all the env variables in a file and use the same appropriately, helps in better versioning, since, it Stores configurations in the environment separate from code.

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.

Usage 1. Create a .env file

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

2.process.env now has the keys and values you defined in your .env file.

const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Upvotes: 0

DumTux
DumTux

Reputation: 726

You can use ShellJS.

var shell = require('shelljs');
shell.echo('APP_VERSION="0.0.1"');

Upvotes: 0

Related Questions