Max SchmittMS
17th July 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?

~/demo $ node main.js
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.

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:

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:

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!

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, feel free to contact me.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.