How do I debug "Error: spawn ENOENT" on node.js?

557,553

Solution 1

How to research the spawn call raising the error:

Known, usual causes

  1. Environment issues

    • The command executable does not exist within the system (dependency not being installed). see prominc's answer
    • The command executable does not exist within a directory of those specified by PATH environment variable.
    • The executable binary was compiled with uncompatible libraries. see danilo-ramirez answer
  2. Windows-only bugs/quirks

  3. Wrong spawn('command', ['--argument', 'list'], { cwd, env, ...opts }) usage

    • Specified working directory (opts.cwd) does not exist · see leeroy-brun's answer
    • Argument list within command String spawn('command --wrong --argument list')
    • Env vars within command string spawn('ENV_VAR=WRONG command')
    • Argument list Array specified as String spawn('cmd', '--argument list')
    • Unset PATH env variable spawn('cmd', [], { env: { variable } } => spawn('cmd', [], { env: { ...process.env, variable } }

There are 2 posible origins for ENOENT:

  1. Code you are writing
  2. Code you depend on

When origin is code you depend on, usual cause is an Environment Issue (or windows quirk)


Solution 2

NOTE: This error is almost always caused because the command does not exist, because the working directory does not exist, or from a windows-only bug.

I found a particular easy way to get the idea of the root cause of:

Error: spawn ENOENT

The problem of this error is, there is really little information in the error message to tell you where the call site is, i.e. which executable/command is not found, especially when you have a large code base where there are a lot of spawn calls. On the other hand, if we know the exact command that cause the error then we can follow @laconbass' answer to fix the problem.

I found a very easy way to spot which command cause the problem rather than adding event listeners everywhere in your code as suggested in @laconbass' answer. The key idea is to wrap the original spawn call with a wrapper which prints the arguments send to the spawn call.

Here is the wrapper function, put it at the top of the index.js or whatever your server's starting script.

(function() {
    var childProcess = require("child_process");
    var oldSpawn = childProcess.spawn;
    function mySpawn() {
        console.log('spawn called');
        console.log(arguments);
        var result = oldSpawn.apply(this, arguments);
        return result;
    }
    childProcess.spawn = mySpawn;
})();

Then the next time you run your application, before the uncaught exception's message you will see something like that:

spawn called
{ '0': 'hg',
  '1': [],
  '2':
   { cwd: '/* omitted */',
     env: { IP: '0.0.0.0' },
     args: [] } }

In this way you can easily know which command actually is executed and then you can find out why nodejs cannot find the executable to fix the problem.

Solution 3

Step 1: Ensure spawn is called the right way

First, review the docs for child_process.spawn( command, args, options ):

Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

The third argument is used to specify additional options, which defaults to:

{ cwd: undefined, env: process.env }

Use env to specify environment variables that will be visible to the new process, the default is process.env.

Ensure you are not putting any command line arguments in command and the whole spawn call is valid. Proceed to next step.

Step 2: Identify the Event Emitter that emits the error event

Search on your source code for each call to spawn, or child_process.spawn, i.e.

spawn('some-command', [ '--help' ]);

and attach there an event listener for the 'error' event, so you get noticed the exact Event Emitter that is throwing it as 'Unhandled'. After debugging, that handler can be removed.

spawn('some-command', [ '--help' ])
  .on('error', function( err ){ throw err })
;

Execute and you should get the file path and line number where your 'error' listener was registered. Something like:

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

If the first two lines are still

events.js:72
        throw er; // Unhandled 'error' event

do this step again until they are not. You must identify the listener that emits the error before going on next step.

Step 3: Ensure the environment variable $PATH is set

There are two possible scenarios:

  1. You rely on the default spawn behaviour, so child process environment will be the same as process.env.
  2. You are explicity passing an env object to spawn on the options argument.

In both scenarios, you must inspect the PATH key on the environment object that the spawned child process will use.

Example for scenario 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);

Example for scenario 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });

The absence of PATH (i.e., it's undefined) will cause spawn to emit the ENOENT error, as it will not be possible to locate any command unless it's an absolute path to the executable file.

When PATH is correctly set, proceed to next step. It should be a directory, or a list of directories. Last case is the usual.

Step 4: Ensure command exists on a directory of those defined in PATH

Spawn may emit the ENOENT error if the filename command (i.e, 'some-command') does not exist in at least one of the directories defined on PATH.

Locate the exact place of command. On most linux distributions, this can be done from a terminal with the which command. It will tell you the absolute path to the executable file (like above), or tell if it's not found.

Example usage of which and its output when a command is found

> which some-command
some-command is /usr/bin/some-command

Example usage of which and its output when a command is not found

> which some-command
bash: type: some-command: not found

miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.

When command is a simple script file ensure it's accessible from a directory on the PATH. If it's not, either move it to one or make a link to it.

Once you determine PATH is correctly set and command is accessible from it, you should be able to spawn your child process without spawn ENOENT being thrown.

Solution 4

As @DanielImfeld pointed it, ENOENT will be thrown if you specify "cwd" in the options, but the given directory does not exist.

Solution 5

in windows, simply adding shell: true option solved my problem:

incorrect:

const { spawn } = require('child_process');
const child = spawn('dir');

correct:

const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});
Share:
557,553
laconbass
Author by

laconbass

I love rhythm. The rhythm in music, at the flow of source code lines, at life... I love following that rhythm, break it down, faster, slowler, STOP. And start again... #SOreadytohelp

Updated on July 08, 2022

Comments

  • laconbass
    laconbass almost 2 years

    When I get the following error:

    events.js:72
            throw er; // Unhandled 'error' event
                  ^
    Error: spawn ENOENT
        at errnoException (child_process.js:1000:11)
        at Process.ChildProcess._handle.onexit (child_process.js:791:34)
    

    What procedure can I follow to fix it?

    Author note: Lots of issues with this error encouraged me to post this question for future references.

    Related questions:

  • Adam Monsen
    Adam Monsen about 9 years
    Here's another idea: just change spawn() to exec() and try again. exec() will tell you what command it tried to run.
  • fredrikekelund
    fredrikekelund about 9 years
    The problem for me was indeed that PATH was undefined. Do you know what causes this? I asked a question about it as well stackoverflow.com/questions/29652582/…
  • laconbass
    laconbass about 9 years
    I remember a time it was undefined because the way I was spawning the node proccess.
  • Dan Nissenbaum
    Dan Nissenbaum almost 9 years
    Important: Make sure to place the code above as close to the start of the main JS file as possible. If you load other modules first, they can stash away the 'spawn' function and the override here will never be called.
  • CodeManiak
    CodeManiak almost 9 years
    This has been very helpful to my debugging of Spawn ENOENT. I've referenced it multiple times. Thanks!
  • Alexander Mills
    Alexander Mills over 8 years
    if it's an ENOENT error, why would the command not be recognized on the OS? it seems reasonable that the command is recognized but something is wrong with reading the file itself...
  • laconbass
    laconbass over 8 years
    @AlexMills Usually the situation you describe is reported as EACCES
  • Daniel Imfeld
    Daniel Imfeld over 8 years
    I've also found that ENOENT will be thrown if you specify cwd in the options, but the given directory does not exist.
  • GreenAsJade
    GreenAsJade over 8 years
    @DanielImfeld TOTAL SAVIOUR. You should write an answer that says this.
  • cdaringe
    cdaringe about 8 years
    I have a linux box and an osx box, both node versions reporting using v4.2.4. On the OSX machine if a try/catch wrap a call to spawn('bogus-binary', ...), it lands in the catch statement. in the linux box, it shows up in the event emitter. this is wild.
  • laconbass
    laconbass about 8 years
    @cdaringe please post a new question with the code and let's see what the problem may be
  • Nilzor
    Nilzor about 8 years
    And what's the solution?
  • Nilzor
    Nilzor about 8 years
    Using node-cross-spawn worked for me. See answer below: stackoverflow.com/a/35561971/507339
  • laconbass
    laconbass about 8 years
    Thinking on refactoring my answer to provide a "general guide", and leaving details to each cause of the problem (miss dependencies, incorrect calls, wrong environment,...).
  • anty
    anty over 7 years
    When you are using spawn('some-command', ['--help'], { env: env }); as exemplified by Step 3 in this answer and are passing a custom environment, be sure to specify the PATH, for instance: { env: { PATH: process.env.PATH } }. The env option will not inherit variables from your current env by default.
  • reduckted
    reduckted over 7 years
    Spent ages trying to find what was wrong and this ended up being the problem. I gave up on spawn and just used exec instead.
  • Bogdan Trusca
    Bogdan Trusca over 7 years
    worked except it is a drop-in, no need for child_process. Exactly the same way as node's spawn or spawnSync, so it's a drop in replacement. var spawn = require('cross-spawn'); // Spawn NPM asynchronously var child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
  • Emile Bergeron
    Emile Bergeron over 7 years
    This is a duplicate of chayasan's answer
  • newguy
    newguy over 7 years
    I have no luck using the script. It doesn't work at all.
  • Felix Eve
    Felix Eve about 7 years
    So how would you use this method in a grunt file? I'm not sure where to put this.
  • Yann Duran
    Yann Duran about 7 years
    This worked perfectly for me. I just put this at the top of my gulpfile.js file, and bingo bango bongo, spawn logging!
  • Somename
    Somename about 7 years
    Does windows need ImageMagick installed as well? Im testing on windows and getting error
  • Deilan
    Deilan almost 7 years
    Where to do these modifications?
  • laconbass
    laconbass almost 7 years
    Don't quote the arguments inside the array
  • Joel B
    Joel B almost 7 years
    @laconbass This is an obviously trivial example to convey the concept and so the quotes could be removed. However, there are cases where you absolutely need to quote the arguments (for example if you need to pass an argument that has a path with a space in it: "C:\Program Files\..."). I posted it here because, even though it may not have been the cause of your specific error case, it will hopefully help someone else experiencing this cryptic error because of Node's handling of quotes on Windows like I was encountering.
  • laconbass
    laconbass almost 7 years
    node.js already makes some Black Magic and silently quotes arguments "properly". Your example should work without the undocumented option you mention, by unquoting argument inside the array.
  • Mitro
    Mitro over 6 years
    so is there a way to execute in a specific directory the command?
  • Alexander Mills
    Alexander Mills over 6 years
    everyone who likes this answer, may also be interested in this native alternative: gist.github.com/ORESoftware/7bf225f0045b4649de6848f1ea5def4c
  • Tom
    Tom over 5 years
    I was running the command as root/ with sudo so the PATH environment variable was not the same. Step 3 was the step that pointed this out to me. Thanks!
  • Ted Nyberg
    Ted Nyberg over 5 years
    Key part is adding shell: true
  • A Gupta
    A Gupta over 5 years
    This is called as monkey patching ! :)
  • Troncoso
    Troncoso over 5 years
    Just to add my own experience, I was running a java process from node. This error happened to me because of quotes around the command, rather than the argument. Test with spaces in the command path and it still works without quotes
  • demisx
    demisx over 5 years
    Hmm... Didn't work for me. Placed it at the top of gulpfile.js
  • Museful
    Museful over 5 years
    In Windows (7) it seems you also need to include the drive letter in the cwd path: 'c:/...' and not just '/...'
  • Nickofthyme
    Nickofthyme over 5 years
    I was able to solve my issue by passing shell: true to the spawn options.
  • laconbass
    laconbass over 5 years
    While this may be a solution for win specific fixes, I don't see how it helps to debug the real cause of the ENOENT
  • Darius
    Darius about 5 years
    Replace console.log(arguments) with console.log(JSON.stringify(arguments, null, 4)) in case of nested (non-circular) objects that you want to print
  • givanse
    givanse about 5 years
    Downvoted because if what you want to have is a shell then you should use child_process.exec or pass shell: true to spawn.
  • Alexander Mills
    Alexander Mills about 5 years
    @givanse not necessarily true - you may want to run zsh or bash or fsh depending on what shell you want to use, and the behavior is also different
  • Matt Molnar
    Matt Molnar about 5 years
    Also, if your Node process is running inside a container like Docker, make sure the command you're trying to run has been added to the Dockerfile
  • Mathieu CAROFF
    Mathieu CAROFF almost 5 years
    I have no idea why, but the spawn call would work in the node repl without the .cmd, but fail in a typescript jest test. -- This error can be quite hard to figure out, this answers deserves more upvotes.
  • Nick
    Nick about 4 years
    Wow such a simple solution and it worked for me! Everyone should try this first to see if it solves the issue.
  • laconbass
    laconbass almost 4 years
    Again, related do filesystem path some way. The extension probably can't reach a path without admin permissions
  • laconbass
    laconbass almost 4 years
    do you know the minimum node --version to be able to use this technique?
  • Kalle Richter
    Kalle Richter almost 4 years
    @laconbass No. I think that's a good SO question which will be anwered within hours.
  • laconbass
    laconbass almost 4 years
    Just got curious. It's way better and cleaner than answer I've checked as accepted
  • MrYellow
    MrYellow almost 4 years
    Another issue is that shell MUST be a simple file path with no arguments. To setup a shell like Docker or similar where args need to be passed it must be wrapped in a proxy bash script.
  • laconbass
    laconbass almost 4 years
  • MrYellow
    MrYellow almost 4 years
    @laconbass Yeah that overloading of spawn works, although the call in my case was buried within a module, made sense to use a bash script (which cleanly accepted -c command only) to call the actual shell with arguments (innershell --foo $1 "$2") rather than monkey patching it deeply within the JS.
  • laconbass
    laconbass almost 4 years
    @MrYellow NODE_DEBUG=child_process may also help avoiding the monkey-patching solution => stackoverflow.com/a/58474965/1894803
  • bFunc
    bFunc over 3 years
    Thanks! This fixed my issue, no need to define cmd or path
  • Marcello de Sales
    Marcello de Sales over 3 years
    I was executing execa with "ab" command, but "Apache Bench" was not installed in the container... So, the first "Environment Issues" case...
  • laconbass
    laconbass over 3 years
    The .cmd extension thing is already covered by existing answers
  • Gal Bracha
    Gal Bracha over 3 years
    Running yarn (To install) fixed it
  • laconbass
    laconbass almost 3 years
    Your issue seems more related to npm itself rather than to node's child_process.spawn(). And seems like a windows quirk
  • John Vandivier
    John Vandivier almost 3 years
    miss-installed programs or non-interoperable installations (even when both may follow the documentation). Example: I installed python via amazon-linux-extras on Amazon Linux 2 but it installed to the entity python3.8 where PythonShell library for Node expected to invoke python3. I aliased the first to the second and continued failure. Now, change the installation to directly yum install python3 and remove the alias - no issue anymore.
  • John Vandivier
    John Vandivier almost 3 years
    the command does not exist agree, or sometimes even when it does exist but only as an alias
  • laconbass
    laconbass over 2 years
    Thanks for the tip
  • Paul
    Paul over 2 years
    Simply run brew install imagemagick
  • AmiNadimi
    AmiNadimi about 2 years
    The first two lines of this answer fixed my problem!
  • Topher Fangio
    Topher Fangio about 2 years
    Adding { shell: true } works on MacOS as well.