Home > Blockchain >  Execute bash script via Node.js and include command line parameters
Execute bash script via Node.js and include command line parameters

Time:11-22

I'm trying to execute a bash script from a Node application, which I have previously done successfully via:

var spawn = require('child_process').spawn;
spawn('bash', [pathToScript], {
    stdio: 'ignore',
    detached: true
}).unref();

It's important that I do it this way, because the script needs to continue to execute, even if/when the application is stopped.

Now, the script I need to execute requires an input value to be provided on the command line, ie.

./myScript.sh hello

But I cannot figure out how to pass this into the spawn call. I have tried the following, with no luck

var spawn = require('child_process').spawn;
spawn('bash', [pathToScript   ''   params], {
    stdio: 'ignore',
    detached: true
}).unref();

CodePudding user response:

The second parameter in spawn is an array of arguments to pass to the command. So I think you almost have it but instead of concating the params to the path pass them in as an array:

var spawn = require('child_process').spawn;
var params = ['pathToScript','run', '-silent'];
spawn('bash', params, {
    stdio: 'ignore',
    detached: true
}).unref();
  • Related