andy
andy

Reputation: 565

how to pass shell script variable to node app.js?

I have prepared the shell script to launch the node application (written using express framework). Shell script looks like below-

#!/bin/bash
cd <NODE.JS Project directory>
npm install --save
var1="connect_point1";
var2="connect_point2";
node app.js var1 var2

in app.js have included below lines-

//print process.argv
process.argv.for Each((val, index) => {console.log('${index}: ${val}');});
var cp1=var1;
var cp2=var2;

I am unable to get var1,var2 values which is passed from shell script to use it in node app.js script. Please suggest me correct way to achieve this.

In the log can see the variable var1 and var2 not defined. so issue is when i am trying to pass the shell script variable to node app.js script..pls suggest me how to pass those parameter correctly, so it can be used in ap.js and other subsequent node scripts.

Upvotes: 2

Views: 2052

Answers (1)

Alexander
Alexander

Reputation: 12785

Add a $ sign to your arguments inside bash script to indicate variables.

#!/bin/bash

var1="connect_point1"
var2="connect_point2"

node app.js $var1 $var2

app.js

process.argv.forEach((index, value) => console.log(index, value));

This is the output i see when running the above bash script:

./bash_script.sh
/usr/local/Cellar/node/12.4.0/bin/node 0
/Users/Username/Temp/app.js 1
connect_point1 2
connect_point2 3

here you can see that the argument values you need are located on index 2 and 3:

var cp1 = process.argv[2];
var cp2 = process.argv[3];

Upvotes: 3

Related Questions