Revenant
Revenant

Reputation: 327

How to use child_process to execute multi commands?

I want to use spawn to execute like

  cd ../ && ls

I tried

const { spawn } = require('child_process');
spawn('cd', ['../', '&&', 'ls'], {
    stdio: 'inherit',
});

But failed with:

Error: spawn cd ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    [... lines matching original stack trace ...]
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

I've googled for this problem for a while, but got no good idea, please help me...

Upvotes: 1

Views: 553

Answers (1)

Mureinik
Mureinik

Reputation: 311028

&& is a shell operator. In order to use it, you'll need to specify shell: true when spawning, and have the entire "chain" as a command, not as arguments:

const { spawn } = require('child_process');
spawn('cd .. && ls', {
    shell: true,
    stdio: 'inherit',
});

Upvotes: 1

Related Questions