Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access shell variable value from Node.js?

Let's say there is a variable key1 and its value is 123

key1=123

so when I run the command in linux environment echo $key1, I get output as 123.

enter image description here

Now I have the following gulp task.

const child_process = require('child_process');
....
gulp.task('printKeyValue', function() {
    var value1 = child_process.execSync('echo $key1');
    console.log(value1.toString().trim());
});

Here, I'm trying to access value of linux variable from nodejs by using Child Process

But when I run the following gulp task, I don't get the desired output.

npm run gulp -- printKeyValue

Instead I get output as $key1 and not 123.

See below screenshot

enter image description here

Other commands like ls & pwd in gulp task gives the desired output.

Can some one please help on this or suggest an alternate way?

like image 295
Siddarth Avatar asked Jun 20 '26 07:06

Siddarth


1 Answers

You are not exporting the variable. When you just do

key1=123

the variable is not propagated to subprocesses. It will be available in your current bash process, so you can see it when you type echo $key1, but it will not get inherited by the node process. As man bash says:

When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell.

  • [...]

  • shell variables and functions marked for export, along with variables exported for the command, passed in the environment

You need to either define the variable as exported

export key1=123

or mark an existing variable for export

key1=123
export key1

or launch your node with the modified environment, either via the bash innate capability to do so

key1=123 node code.js

or using /usr/bin/env utility:

env key1=123 node code.js

Once the variable is properly passed to the node process, it will be available both in process.env.key1 and as $key1 in a child process.

EDIT: I just noticed, you actually gave the command you're running; it does not matter, the same logic goes for every executable, whether node or npm or anything else.

like image 163
Amadan Avatar answered Jun 21 '26 20:06

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!