简体   繁体   中英

Execute multiple shell commands synchronously in Node

I have working code that does exactly what I want but I'm not happy with the method I've used because it doesn't scale well.

Say I want to execute 4 commands, one after the other, to clone a repo and checkout a release to a local folder:

//shell command
var cmd = "cd /Users/xxxx/Documents/DESIGN" +
          " && git clone https://github.com/xxxx/xxxx.git testing" + 
          " && cd testing" +
          " && git checkout 4.0"; 

//execute shell command
var exec = require("child_process").exec;
exec(cmd, function(err, stdout, stderr){
  if (err) console.log(err);
  console.log(stdout);
});

Is there a way to cleanly execute multiple commands and make this more scalable without just adding more to the original command string with the && to join them?

there is a lot of stuff you could do. the simplest one would be to use execSync , and execute one command after each other.

as you need commands to be executed one ofter the other, that would be the solution i would go with.

if you want to stick to an asynchronous pattern, use a control-flow-lib like step or async .

you could even promisify exec with a lib like bluebird .

it all depends on personal coding preferences and the task you need to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM