Node JS - 在 Grunt 任务中使用 child_process spawn('npm install') 导致 ENOENT 错误

10

我在撰写一个Grunt任务时遇到了一些困难。我试图执行npm install,然后是bower install,最后是grunt hub target(以触发多个子项目的构建命令)。

我遇到的问题与child_process有关。如果我在我的Grunt任务中运行以下命令,并且当前已注释掉的npm install spawn命令,则会收到spawn ENOENT错误:

    var path = require('path'),
        projectPath = path.resolve(process.cwd(), this.data.activity );

        grunt.log.debug('project path computed as: ', projectPath);
        process.chdir( projectPath );

        console.log('current dir is: ', process.cwd());
        console.log('EVN is: ', process.env);

        var spawnProcess = spawn('ls');
        // var spawnProcess = spawn('npm install');

        spawnProcess.stdout.on('data', function (data) {
            console.log('' + data);
        });

        spawnProcess.stderr.on('data', function(data) {

            console.log('something went wrong installing deps for ' + path + '.  Error: ', data);
        });

        spawnProcess.on('close', function (exitCode) {

            console.log( 'ls has finished with Exit Code: ' + exitCode);
        });

当前的代码(使用 ls 而不是 npm install)会导致:

   running "install:projects" (install) task[D] Task source: /Users/zedd45/proj/Gruntfile.js
Verifying property install.projects exists in config...OK
File: [no files]
[D] project path computed as:  /Users/zedd45/proj/activity/web/client
current dir is:  /Users/zedd45/proj/activity/web/client
EVN (abbreviated) is:  { 
   TERM_PROGRAM: 'iTerm.app',
   SHELL: '/bin/bash',
   PWD: '/Users/zedd45/proj',
 ...
  OLDPWD: '/Users/zedd45/proj/activity/web/client',
  _: '/usr/local/bin/grunt' }

GruntFile.js
bower.json
package.json
this_is_the_directory_you_are_looking_for.txt
ls has finished with Exit Code: 0

但如果我将'ls'更改为'npm install',那么我会得到以下结果:

``致命错误:spawn ENOENT``

紧接着ENV的输出。

我已经尝试对该目录使用chmod 777,但似乎没有帮助。

我也试过:

// var spawnProcess = spawn('npm install', {'cwd': projectPath});

// var spawnProcess = spawn('npm install', [], {'cwd': projectPath});

前者会导致

警告:对象 # 没有方法'slice'。使用 --force 继续。

后者仍然会导致 ENOENT 错误。

关于这个 ENOENT 错误,任何帮助都可能会有很大的帮助。我在Google上搜索和尝试使用子进程API文档都没有太大的成功。

1个回答

13

请再次仔细查阅child_process.spawn文档。第一个参数应该只包含要运行的命令,第二个参数则为参数列表:

var npm = spawn('npm', ['install'], { cwd: projectPath });

1
那个完美地运行了。一旦你提供了解决方案,我简直不敢相信它是如此容易/显而易见的,或者它是如何难以逃脱我的注意力。非常感谢! - zedd45
2
为了可能访问者的未来参考,请转化以下与编程有关的内容为中文。仅返回翻译后的文本:https://dev59.com/SV4c5IYBdhLWcg3wqLte - laconbass
嗯,这对我没用。仍然出现 spawnSync npm ENOENT 错误(是的,我正在使用同步版本)。 - ianbeks
7
在Windows系统中,您需要调用npm.cmd - Kai Sellgren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接