Search code examples
node.jsmultithreadingshellchild-processspawn

Multi-command shell AS detached child process WITH spawn() IN Node.js


For reference: https://nodejs.org/api/child_process.html#child_process_options_detached

Hey guys,

So I need to spawn a child child-process, spawn because exec doesn't allow a options.detached & child.unref();, meaning it can be decoupled with the parent allowing the child to run and finish on it's own, vice-versa also the parent (in our particular case, the parent process can die before a long-running child, update in that case, is finished without needing to wait for the child like with exec).

We have a long connected ("… ; … ; …") command that is built by the node (parent) app, but as like spawn("echo stuff >>stderr.log") doesn't work, only spawn('ls', [-l]), I obviously can't chain commands (as it's also referenced in he docu and multiple times on SO.

TLDR;

We need to use spawn, but spawn can't process chained shell commands. Do I really now need to write my command in a bash and execute that then, is this REALLY the ONLY option??

THX


Solution

  • Notice the shell option for spawn:

    If true, runs command inside of a shell. Uses '/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be specified as a string. The shell should understand the -c switch on UNIX, or /d /s /c on Windows. Defaults to false (no shell).

    So:

    let child = child_process.spawn('foo; bar; blah', { shell : true });
    

    EDIT: if you're using a Node version that doesn't support this option, here's an alternative:

    let child = child_process.spawn('/bin/sh', [ '-c', 'foo; bar; blah' ]);