Error: spawn ENOENT on Windows

I got it. On Windows bunyan isn't recognized in the console as a program but as a command. So to invoke it the use of cmd was needed. I also had to install bunyan globally so that the console could access it.

if (!/^win/.test(process.platform)) { // linux
    var sp = spawn('bunyan', ['-o', 'short'], {
        stdio: [null, process.stdout, process.stderr]
    });
} else { // windows
    var sp = spawn('cmd', ['/s', '/c', 'bunyan', '-o', 'short'], {
        stdio: [null, process.stdout, process.stderr]
    });
}

Use {shell: true} in the options of spawn

I was hit with this problem recently so decided to add my findings here. I finally found the simplest solution in the Node.js documentation. It explains that:

  • child_process.exec() runs with shell
  • child_process.execFile() runs without shell
  • child_process.spawn() runs without shell (by default)

This is actually why the exec and spawn behave differently. So to get all the shell commands and any executable files available in spawn, like in your regular shell, it's enough to run:

const { spawn } = require('child_process')
const myChildProc = spawn('my-command', ['my', 'args'], {shell: true})

or to have a universal statement for different operating systems you can use

const myChildProc = spawn('my-command', ['my', 'args'], {shell: process.platform == 'win32'})

Side notes:

  1. It migh make sense to use such a universal statement even if one primairly uses a non-Windows system in order to achieve full interoperability
  2. For full consistence of the Node.js child_process commands it would be helpful to have spawn (with shell) and spawnFile (without shell) to reflect exec and execFile and avoid this kind of confusions.

Tags:

Node.Js