Node child_process.spawn multiple commands

Даниел Димов picture Даниел Димов · Jan 26, 2016 · Viewed 21k times · Source

I wan to automate the creation and extracting of keystore. The problem I'm facing is how to join the commands using the ' | ' symbol or similar solution.

//Original Command    
var command='keytool -exportcert -storepass mypass -keypass mypass  
-alias myalias -keystore mykey.keystore | openssl sha1 -binary | openssl base64';

//Arguments for the spawn    
var keyArgs = [
      '-exportcert',
      '-storepass','mypass',
      '-keypass','mypass',
      '-alias','myalias',
      '-keystore',"myjey.keystore",


      'openssl','sha1',
      '-binary',
      'openssl','base64',


  ];
exec('keytool',keyArgs,{cwd:appCreateFolder+"/"+opt.id+"/Certificates"},function(e){
    console.log(chalk.cyan('Key created'));
      })

Answer

Jan Jůna picture Jan Jůna · Nov 4, 2016

From Node.js v6 you can specify a shell option in spawn method which will run command using shell and thus it is possible to chain commands using spawn method.

For example this:

var spawn = require('child_process').spawn;
var child = spawn('ls && ls && ls', {
  shell: true
});
child.stderr.on('data', function (data) {
  console.error("STDERR:", data.toString());
});
child.stdout.on('data', function (data) {
  console.log("STDOUT:", data.toString());
});
child.on('exit', function (exitCode) {
  console.log("Child exited with code: " + exitCode);
});

Will trigger an error on node.js version less than 6:

Error: spawn ls && ls && ls ENOENT

But on version 6 and higher it will return expected result:

node app.js
STDOUT: app.js

STDOUT: app.js
app.js

Child exited with code: 0