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

2018-12-31 09:00发布

17条回答
千与千寻千般痛.
2楼-- · 2018-12-31 09:29

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})
    
查看更多
步步皆殇っ
3楼-- · 2018-12-31 09:29

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);
});
查看更多
公子世无双
4楼-- · 2018-12-31 09:30

@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.

查看更多
查无此人
5楼-- · 2018-12-31 09:31

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

查看更多
倾城一夜雪
6楼-- · 2018-12-31 09:31

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.

查看更多
君临天下
7楼-- · 2018-12-31 09:31

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!!

查看更多
登录 后发表回答