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

31

537

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:

Cuirbouilli answered 29/12, 2014 at 12:22 Comment(4)
In my case, I was passing in the whole command as a String like you would with exec instead of passing in the command as the first argument and the options as an Array for the second argument. e.g. I was doing spawn( "adb logcat -c" ) instead of spawn( "adb", [ "logcat", "-c" ] ).Beamends
This worked for me: https://mcmap.net/q/74811/-spawn-python-enoent-node-js-in-windowsLilliamlillian
In VS Code, uninstalled below linter extension, then it worked: marketplace.visualstudio.com/items?itemName=fnando.linter . See github.com/yarnpkg/yarn/issues/5275#issuecomment-1250079916Effects
Again, a missing dependency within environment causeCuirbouilli
C
25

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)


Cuirbouilli answered 29/12, 2014 at 12:22 Comment(1)
I was executing execa with "ab" command, but "Apache Bench" was not installed in the container... So, the first "Environment Issues" case...Malignant
U
306

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.

Ultramicroscope answered 11/1, 2015 at 2:40 Comment(10)
Here's another idea: just change spawn() to exec() and try again. exec() will tell you what command it tried to run.Coda
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.Forefend
I have no luck using the script. It doesn't work at all.Pedaias
So how would you use this method in a grunt file? I'm not sure where to put this.Geminian
This worked perfectly for me. I just put this at the top of my gulpfile.js file, and bingo bango bongo, spawn logging!Hatchet
This is called as monkey patching ! :)Lowell
Hmm... Didn't work for me. Placed it at the top of gulpfile.jsDewy
Replace console.log(arguments) with console.log(JSON.stringify(arguments, null, 4)) in case of nested (non-circular) objects that you want to printAngadreme
the command does not exist agree, or sometimes even when it does exist but only as an aliasNanon
The first two lines of this answer fixed my problem!Crowns
C
159

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.

Cuirbouilli answered 29/12, 2014 at 12:22 Comment(22)
The problem for me was indeed that PATH was undefined. Do you know what causes this? I asked a question about it as well #29653082Synergist
I remember a time it was undefined because the way I was spawning the node proccess.Cuirbouilli
This has been very helpful to my debugging of Spawn ENOENT. I've referenced it multiple times. Thanks!Davena
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...Anthea
@AlexMills Usually the situation you describe is reported as EACCESCuirbouilli
I've also found that ENOENT will be thrown if you specify cwd in the options, but the given directory does not exist.Upali
@DanielImfeld TOTAL SAVIOUR. You should write an answer that says this.Greengage
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.Hauger
@Hauger please post a new question with the code and let's see what the problem may beCuirbouilli
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.Exultation
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!Chism
I was able to solve my issue by passing shell: true to the spawn options.Abduction
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 DockerfileVerst
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.Tomikotomkiel
@Tomikotomkiel see https://mcmap.net/q/73597/-how-do-i-debug-quot-error-spawn-enoent-quot-on-node-jsCuirbouilli
@Cuirbouilli 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.Tomikotomkiel
@Tomikotomkiel NODE_DEBUG=child_process may also help avoiding the monkey-patching solution => https://mcmap.net/q/73597/-how-do-i-debug-quot-error-spawn-enoent-quot-on-node-jsCuirbouilli
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.Nanon
you did beat ChatGPT.. it couldn't help, thought I didn't have command. Apparently I was calling spawn incorrectly. Thanks!Toro
Humans instruct machines. Remember that ;)Cuirbouilli
@DanielImfeld I was running a script where a child process spawn was changing the git branch and then tried to pull from the new branch. Since the script didn't exist in the new branch, I was getting this error (only on Debian, it was working on Macos). Your comment saved me a lot of headache. Thank you!Codeine
Another gotcha : spawn does not respect your bash settings. I had aliased a common build command, and node did not know about the alias. If you're seeing ENOENT, ensure your command is not an alias.Bidget
W
106

simply adding shell: true option solved my problem:

following code is buggy on windows:

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

workaround:

const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});

based on Node.js Documentation (thanks to @Boris comment):

Note that:

if the shell option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.

Winfrid answered 20/1, 2020 at 19:52 Comment(6)
Thanks! This fixed my issue, no need to define cmd or pathIoves
Adding { shell: true } works on MacOS as well.Annabell
Finally resolved my issue after a day! Was operating out of windows and this solved it, thank you so much.Ours
Note that "if the shell option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution."Sitter
That's what fixed my issue, on windows, it couldn't find eslint ... thank you so much :)Altitude
Note this is a windows-only quirk. ENOENT may be thrown on other situationsCuirbouilli
Z
46

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

Zoochore answered 17/6, 2016 at 14:44 Comment(2)
so is there a way to execute in a specific directory the command?Hanselka
In Windows (7) it seems you also need to include the drive letter in the cwd path: 'c:/...' and not just '/...'Virtuous
E
33

Windows solution: Replace spawn with node-cross-spawn. For instance like this at the beginning of your app.js:

(function() {
    var childProcess = require("child_process");
    childProcess.spawn = require('cross-spawn');
})(); 
Ellen answered 22/2, 2016 at 19:16 Comment(1)
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' });Ennui
A
32

@laconbass's answer helped me and is probably most correct.

I came here because I was using spawn incorrectly. As a simple example:

this is incorrect:

const s = cp.spawn('npm install -D suman', [], {
    cwd: root
});

this is incorrect:

const s = cp.spawn('npm', ['install -D suman'], {
    cwd: root
});

this is correct:

const s = cp.spawn('npm', ['install','-D','suman'], {
    cwd: root
});

however, I recommend doing it this way:

const s = cp.spawn('bash');
s.stdin.end(`cd "${root}" && npm install -D suman`);
s.once('exit', code => {
   // exit
});

this is because then the cp.on('exit', fn) event will always fire, as long as bash is installed, otherwise, the cp.on('error', fn) event might fire first, if we use it the first way, if we launch 'npm' directly.

Anthea answered 12/4, 2016 at 1:32 Comment(4)
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,...).Cuirbouilli
everyone who likes this answer, may also be interested in this native alternative: gist.github.com/ORESoftware/7bf225f0045b4649de6848f1ea5def4cAnthea
Downvoted because if what you want to have is a shell then you should use child_process.exec or pass shell: true to spawn.Cheerful
@Cheerful 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 differentAnthea
B
32

For ENOENT on Windows, https://github.com/nodejs/node-v0.x-archive/issues/2318#issuecomment-249355505 fix it.

e.g. replace spawn('npm', ['-v'], {stdio: 'inherit'}) with:

  • for all node.js version:

    spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['-v'], {stdio: 'inherit'})
    
  • for node.js 5.x and later:

    spawn('npm', ['-v'], {stdio: 'inherit', shell: true})
    
Bialystok answered 25/9, 2016 at 2:22 Comment(2)
Where to do these modifications?Felisha
Key part is adding shell: trueImmingle
C
25

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)


Cuirbouilli answered 29/12, 2014 at 12:22 Comment(1)
I was executing execa with "ab" command, but "Apache Bench" was not installed in the container... So, the first "Environment Issues" case...Malignant
S
22

For anyone who might stumble upon this, if all the other answers do not help and you are on Windows, know that there is currently a big issue with spawn on Windows and the PATHEXT environment variable that can cause certain calls to spawn to not work depending on how the target command is installed.

Scarberry answered 5/8, 2015 at 19:37 Comment(3)
And what's the solution?Ellen
Using node-cross-spawn worked for me. See answer below: https://mcmap.net/q/73597/-how-do-i-debug-quot-error-spawn-enoent-quot-on-node-jsEllen
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.Wellrounded
L
11

In my case, I was getting this error thrown due to the necessary dependent system resources not being installed.

More specifically, I have a NodeJS app that is utilizing ImageMagick. Despite having the npm package installed, the core Linux ImageMagick was not installed. I did an apt-get to install ImageMagick and after that all worked great!

Lucia answered 12/6, 2015 at 20:1 Comment(3)
Does windows need ImageMagick installed as well? Im testing on windows and getting errorHypocotyl
Running yarn (To install) fixed itBrigettebrigg
Simply run brew install imagemagickCorinacorine
U
11

Before anyone spends to much time debugging this problem, most of the time it can be resolved by deleting node_modules and reinstalling the packages.

To Install:

If a lockfile exists you might use

yarn install --frozen-lockfile

or

npm ci

respectivly. if not then

yarn install

or

npm i
Unstudied answered 14/2, 2020 at 12:9 Comment(1)
Wow such a simple solution and it worked for me! Everyone should try this first to see if it solves the issue.Nanaam
G
6

Are you changing the env option?

Then look at this answer.


I was trying to spawn a node process and TIL that you should spread the existing environment variables when you spawn else you'll loose the PATH environment variable and possibly other important ones.

This was the fix for me:

const nodeProcess = spawn('node', ['--help'], {
  env: {
    // by default, spawn uses `process.env` for the value of `env`
    // you can _add_ to this behavior, by spreading `process.env`
    ...process.env,
    OTHER_ENV_VARIABLE: 'test',
  }
});
Goodwin answered 24/9, 2019 at 17:44 Comment(0)
A
6

In case you're experiencing this issue with an application whose source you cannot modify consider invoking it with the environment variable NODE_DEBUG set to child_process, e.g. NODE_DEBUG=child_process yarn test. This will provide you with information which command lines have been invoked in which directory and usually the last detail is the reason for the failure.

Amur answered 20/10, 2019 at 16:26 Comment(3)
do you know the minimum node --version to be able to use this technique?Cuirbouilli
@Cuirbouilli No. I think that's a good SO question which will be anwered within hours.Amur
Just got curious. It's way better and cleaner than answer I've checked as acceptedCuirbouilli
B
3

I had this appear while building gulp-jekyll in Powershell on Windows 11.

nodejs 10 LTS, gulp v3.9.1, ruby 3.1, bundler 2.4.5, jekyll 4.2.2

This line of code here is the cause of the ENOENT issue I had with spawn and bundle.

  return cp.spawn('bundle', [
    'exec', 
    'jekyll', 
    'build', 
    '--source=app', '--destination=build/development', '--config=_config.yml', '--profile'
  ], { stdio: 'inherit' })
  .on('close', done);

Two errors returned, and troubleshooting should start here. 🤓🧐

events.js:174
      throw er; // Unhandled 'error' event
      ^
Error: spawn bundle ENOENT

The cp.spawn is not handling an error Event, so handling that with a simple console.log() will expose the real error with debug information:

  return cp.spawn('bundle', [
    'exec', 
    'jekyll', 
    'build', 
    '--source=app', '--destination=build/development', '--config=_config.yml', '--profile'
  ], { stdio: 'inherit' })
  .on('error', (e) => console.log(e))
  .on('close', done);

This now provides a lot more information to debug with.

{ Error: spawn bundle ENOENT
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'spawn bundle',
  path: 'bundle',
  spawnargs:
   [ 'exec',
     'jekyll',
     'build',
     '--source=app',
     '--destination=build/development',
     '--config=_config.yml',
     '--profile' ] }

The next step to debug would be using the nodejs 10 LTS documentation for child_process.spawn(command[, args][, options]). As already described above, adding the { shell: true } to the options of spawn is a working solution. This is what solved my problem as well. 😌

  { stdio: 'inherit', shell: true }

This solution is merely a band-aid and could be refactored to handle all environments, but that is out of scope for how to troubleshoot & debug the spawn ENOENT error on nodejs.

Beezer answered 29/1, 2023 at 2:7 Comment(0)
B
2

I ran into the same problem, but I found a simple way to fix it. It appears to be spawn() errors if the program has been added to the PATH by the user (e.g. normal system commands work).

To fix this, you can use the which module (npm install --save which):

// Require which and child_process
const which = require('which');
const spawn = require('child_process').spawn;
// Find npm in PATH
const npm = which.sync('npm');
// Execute
const noErrorSpawn = spawn(npm, ['install']);
Buccinator answered 21/5, 2016 at 19:2 Comment(0)
T
2

Use require('child_process').exec instead of spawn for a more specific error message!

for example:

var exec = require('child_process').exec;
var commandStr = 'java -jar something.jar';

exec(commandStr, function(error, stdout, stderr) {
  if(error || stderr) console.log(error || stderr);
  else console.log(stdout);
});
Taddeusz answered 3/6, 2017 at 8:51 Comment(0)
V
2

A case that I found that is not in this list but it's worthy to be added:

On Alpine Linux, Node will error with ENOENT if the executable is not compatible.

Alpine expects binaries with libc. An executable (e.g. chrome as part of chromium) that has been compiled with glibc as a wrapper for system calls, will fail with ENOENT when called by spawn.

Valdovinos answered 28/12, 2021 at 0:6 Comment(1)
yes this is the issue. In order to fix this follow this github.com/facebook/flow/issues/3649#issuecomment-447115855Ulpian
A
1

Ensure module to be executed is installed or full path to command if it's not a node module

Alten answered 25/12, 2016 at 20:50 Comment(0)
L
1

I was also going through this annoying problem while running my test cases, so I tried many ways to get across it. But the way works for me is to run your test runner from the directory which contains your main file which includes your nodejs spawn function something like this:

nodeProcess = spawn('node',params, {cwd: '../../node/', detached: true });

For example, this file name is test.js, so just move to the folder which contains it. In my case, it is test folder like this:

cd root/test/

then from run your test runner in my case its mocha so it will be like this:

mocha test.js

I have wasted my more than one day to figure it out. Enjoy!!

Lauryn answered 13/3, 2018 at 8:21 Comment(0)
B
1

solution in my case

var spawn = require('child_process').spawn;

const isWindows = /^win/.test(process.platform); 

spawn(isWindows ? 'twitter-proxy.cmd' : 'twitter-proxy');
spawn(isWindows ? 'http-server.cmd' : 'http-server');
Brouwer answered 9/11, 2018 at 22:0 Comment(3)
While this may be a solution for win specific fixes, I don't see how it helps to debug the real cause of the ENOENTCuirbouilli
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.Undressed
The .cmd extension thing is already covered by existing answersCuirbouilli
T
1

I ran into this problem on Windows, where calling exec and spawn with the exact same command (omitting arguments) worked fine for exec (so I knew my command was on $PATH), but spawn would give ENOENT. Turned out that I just needed to append .exe to the command I was using:

import { exec, spawn } from 'child_process';

// This works fine
exec('p4 changes -s submitted');

// This gives the ENOENT error
spawn('p4');

// But this resolves it
spawn('p4.exe');
// Even works with the arguments now
spawn('p4.exe', ['changes', '-s', 'submitted']);
Toitoiboid answered 9/8, 2019 at 16:35 Comment(0)
M
0

I was getting this error when trying to debug a node.js program from within VS Code editor on a Debian Linux system. I noticed the same thing worked OK on Windows. The solutions previously given here weren't much help because I hadn't written any "spawn" commands. The offending code was presumably written by Microsoft and hidden under the hood of the VS Code program.

Next I noticed that node.js is called node on Windows but on Debian (and presumably on Debian-based systems such as Ubuntu) it's called nodejs. So I created an alias - from a root terminal, I ran

ln -s /usr/bin/nodejs /usr/local/bin/node

and this solved the problem. The same or a similar procedure will presumably work in other cases where your node.js is called nodejs but you're running a program which expects it to be called node, or vice-versa.

Malvaceous answered 28/2, 2016 at 0:20 Comment(0)
L
0

If you're on Windows Node.js does some funny business when handling quotes that may result in you issuing a command that you know works from the console, but does not when run in Node. For example the following should work:

spawn('ping', ['"8.8.8.8"'], {});

but fails. There's a fantastically undocumented option windowsVerbatimArguments for handling quotes/similar that seems to do the trick, just be sure to add the following to your opts object:

const opts = {
    windowsVerbatimArguments: true
};

and your command should be back in business.

 spawn('ping', ['"8.8.8.8"'], { windowsVerbatimArguments: true });
Lefthand answered 18/6, 2017 at 0:48 Comment(4)
Don't quote the arguments inside the arrayCuirbouilli
@Cuirbouilli 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.Lefthand
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.Cuirbouilli
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 quotesAntonietta
I
0

Although it may be an environment path or another issue for some people, I had just installed the Latex Workshop extension for Visual Studio Code on Windows 10 and saw this error when attempting to build/preview the PDF. Running VS Code as Administrator solved the problem for me.

Ironlike answered 2/5, 2020 at 22:43 Comment(1)
Again, related do filesystem path some way. The extension probably can't reach a path without admin permissionsCuirbouilli
B
0

In my case removing node, delete all AppData/Roaming/npm and AppData/Roaming/npm-cache and installing node once again solve the issue.

Berberine answered 6/8, 2020 at 8:41 Comment(0)
P
0

Recently I also faced similar issue.

Starting the development server...

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

Error: spawn null ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
error Command failed with exit code 1.

It was due to having a wrong configuration in .env file for BROWSER. I had BROWSER=null, but it has to be BROWSER=none. Changing that configuration resolved my issue.

Positron answered 24/3, 2021 at 19:8 Comment(0)
H
0

Tried all nothing worked , my system has different issue .

The working solution for me is run command : npm config set script-shell "C:\Program Files\git\bin\bash.exe"

Hygienics answered 7/5, 2021 at 11:41 Comment(1)
Your issue seems more related to npm itself rather than to node's child_process.spawn(). And seems like a windows quirkCuirbouilli
Q
-1

I got the same error for windows 8.The issue is because of an environment variable of your system path is missing . Add "C:\Windows\System32\" value to your system PATH variable.

Qatar answered 6/5, 2016 at 11:48 Comment(0)
C
-1

Local development on Emulator

Make sure to have the package installed locally. By changing the spawn command with exec i got a more detailed error and found out I didn't install the package. Simply run, to check if the package is present:

brew install imagemagick

Source

Corinacorine answered 6/1, 2022 at 16:45 Comment(0)
C
-3

Add C:\Windows\System32\ to the path environment variable.

Steps

  1. Go to my computer and properties

  2. Click on Advanced settings

  3. Then on Environment variables

  4. Select Path and then click on edit

  5. Paste the following if not already present: C:\Windows\System32\

  6. Close the command prompt

  7. Run the command that you wanted to run

Windows 8 Environment variables screenshot

Chariot answered 13/8, 2016 at 17:49 Comment(1)
This is a duplicate of chayasan's answerDuring
F
-4

For me I made following changes in package.json.

  "version": "0.0.0",
  "scripts": {
    "dev": "vite --open",    // delete this line
    "dev": "vite",           // with this one
   .....
  }
Furmark answered 15/9, 2022 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.