错误:产生npm ENOENT

Arm*_*yan 15 javascript windows node.js

我有一个JS应用程序.它在linux上运行良好但在Windows 10中我收到错误.

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

Error: spawn npm ENOENT
    at exports._errnoException (util.js:1028:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
    at onErrorNT (internal/child_process.js:359:16)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Module.runMain (module.js:607:11)
    at run (bootstrap_node.js:422:7)
    at startup (bootstrap_node.js:143:9)
    at bootstrap_node.js:537:3
Run Code Online (Sandbox Code Playgroud)

并且不正确的代码就是这个

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

const watching = [
  // {service: "babel-watch"},
  {service: "webpack-watch"},
  // {service: "sass-watch"},
  {service: "server-watch"}
];

watching.forEach(({service}) => {
  const child = spawn('npm', ['run', service]);
  child.stdout.on('data', d => console.log(d.toString()));
  child.stderr.on('data', d => console.log(d.toString()));
});
Run Code Online (Sandbox Code Playgroud)

我在github中发现了这个错误的原因我想问题是spawn nodejs spawn Doc在Windows中无法正常工作.但我不知道如何修改这段代码以使其工作.有人能帮我吗 ?

Arm*_*yan 45

刚改变了这一行

const child = spawn('npm', ['run', service]);
Run Code Online (Sandbox Code Playgroud)

到这条线

  const child = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['run',  service]);
Run Code Online (Sandbox Code Playgroud)

如果操作系统是运行npm.cmd的话,那就是检查操作系统,如果它是linux只是npm

  • 奇怪,因为我可以按命令正常调用 npm 本身,但这肯定也解决了我的问题。救生员。 (2认同)

Cav*_*ava 7

我知道有一个正确的答案,并且这个问题已经存在很长时间了,我的解决方案基于答案@Armen Sanoyan 以及How do I certain the current Operating system with Node.js

对我来说,@Armen Sanoyan 的答案不起作用,但有很大帮助。我为了这一行和工作而改变。

const child = (process.platform === 'win32' ? 'npm.cmd' : 'npm') + ' run ' + service;
Run Code Online (Sandbox Code Playgroud)

我希望我能帮忙。