通过Grunt运行Node应用程序

13 process spawn node.js gruntjs

我正在尝试将我的Node应用程序作为Grunt任务运行.但是,我需要将其作为子进程生成,以允许我并行运行监视任务.

这有效:

grunt.registerTask('start', function () {
  grunt.util.spawn(
    { cmd: 'node'
    , args: ['app.js']
    })

  grunt.task.run('watch:app')
})
Run Code Online (Sandbox Code Playgroud)

但是,当监视任务检测到更改时,这将再次触发启动任务.在我生成我的Node应用程序的另一个子进程之前,我需要杀死前一个.

但是,我无法弄清楚如何杀死这个过程.这样的东西不起作用:

var child

grunt.registerTask('start', function () {
  if (child) child.kill()
  child = grunt.util.spawn(
    { cmd: 'node'
    , args: ['app.js']
    })

  grunt.task.run('watch:app')
})
Run Code Online (Sandbox Code Playgroud)

看起来:

  1. 即使我将生成的进程存储在函数上下文之外的变量中,它也不会持久存在,因此下次启动任务时,child就是undefined.
  2. child没有kill功能......

gle*_*itz 5

看一下grunt-nodemon,它处理与产生子进程相关的许多麻烦.


Kyl*_*ung 4

这是因为grunt-contrib-watch当前将所有任务运行作为子进程生成。因此该变量child不在同一进程上下文中。很快,grunt-contrib-watch@0.3.0就会发布一个nospawn选项。这将允许您将手表配置为在同一上下文中生成任务运行,并使上面的示例正常工作。

查看此问题以获取更多信息:

https://github.com/gruntjs/grunt-contrib-watch/issues/45