Max Schmitt

July 17 2019

How to fix "Error: spawn node ENOENT" when using child_process in Node.js

Have you ever stumbled upon this error when using spawn from Node.js' child_process module?

Terminal

~/demo $ node main.js
~/demo/main.js:10
throw err;
^
Error: spawn node ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:264:19)
at onErrorNT (internal/child_process.js:456:16)
at processTicksAndRejections (internal/process/task_queues.js:77:11)

I keep running into this error over and over again. And what confuses me every time is that I could always swear that the given piece of code was working before.

JS

const { spawn } = require('child_process')
// ✅ This works:
spawn('node', ['script.js'])

It turns out that when you pass in options.env as the third argument to set an environment variable on the child process, the error appears:

JS

const { spawn } = require('child_process')
// ❌ This doesn't work:
spawn('node', ['script.js'], {
env: { NODE_ENV: 'production' },
})

To fix it, simply pass along the PATH environment variable from the parent process as well:

JS

const { spawn } = require('child_process')
// ✅ This works:
spawn('node', ['script.js'], {
env: {
NODE_ENV: 'production',
PATH: process.env.PATH,
},
})

The reason the spawn was broken in the first place was because we were overriding the child process' environment variables in options.env which it normally would have inherited from its parent process.

So without the PATH environment variable, the operating system doesn't know where to look for the node executable.

I hope this helped!