Grunt任务输出,然后调用grunt-notify

Grunt通知: https : //github.com/dylang/grunt-notify是伟大的。 但是,这似乎有点有限。 据我可以告诉我所有的消息需要预先生成。 所以第一个问题是我怎样才能生成通知?

接下来,似乎基于错误或某个任务的成功,grunt通知触发器。 我猜基于std in / out / err? 这种情况下,问题是如果一些任务不使用这些。 如果有编译错误,grunt指南针不使用stderr。 那么如何在发生错误时运行grunt通知? 这会导致下一个问题。 我如何从一个咕task任务抓住控制台输出或标准错误?

首先,使用咆哮 。 使用起来简单而灵活。 要安装咆哮

npm install growl --save-dev 

然后你需要挂钩进程的stderr / outstream。 这样,每当新邮件到达stderr / outstream时,您都可以创build通知。

这是我创造的。 我做了一个CommonJs模块,它增加了钩子:

  • grunt.fail.warn()grunt.fail.fatal()
  • grunt.log.warn()grunt.log.error()
  • grunt.warn()
  • process.stderr.write()
  • process.stdout.write() (错误行)
  • (child) process.stderr.write()
  • (子) process.stdout.write() (错误行)

它或多或less起作用,但可能需要一些调整。

任务/ lib目录/ notify.js

 (function (module) { var grunt = require('grunt'), growl = require('growl'), Buffer = require('buffer').Buffer; function notify(obj, title) { if (obj) { var message = Buffer.isBuffer(obj) ? obj.toString() : (obj.message || obj); var msg = grunt.log.uncolor(message); if (msg.length > 0) { growl(msg, { title: title, image: 'Console' }); } } } // add a hook to grunt.fail.warn(), grunt.fail.fatal() ['warn', 'fatal'].forEach(function (level) { grunt.util.hooker.hook(grunt.fail, level, function(obj) { notify(obj); }); }); // add a hook to grunt.log.warn(), grunt.log.error() ['warn', 'error'].forEach(function (level) { grunt.util.hooker.hook(grunt.log, level, function(obj) { notify(obj, level); }); }); // add a hook to grunt.warn() grunt.util.hooker.hook(grunt, 'warn', function(obj) { notify(obj, 'warn'); }); // add a hook to process.stderr.write() grunt.util.hooker.hook(process.stderr, 'write', function(obj) { var messages = grunt.log.uncolor((Buffer.isBuffer(obj) ? obj.toString() : (obj.message || obj))).split('\n'); messages.forEach(function (message) { notify(message, 'stderr'); }); }); // add a hook to process.stdout.write() (only error lines) grunt.util.hooker.hook(process.stdout, 'write', function(obj) { var messages = grunt.log.uncolor((Buffer.isBuffer(obj) ? obj.toString() : (obj.message || obj))).split('\n'); messages.forEach(function (message) { if (message && message.indexOf('error ') > -1) { notify(message, 'stdout'); } }); }); // add a hook to child process stdout/stderr write() (only error lines) grunt.util.hooker.hook(grunt.util, 'spawn', { post: function(child) { child.stderr.on('data', function (data) { var messages = grunt.log.uncolor(data.toString()).split('\n'); messages.forEach(function (message) { notify(message, 'stderr'); }); }); child.stdout.on('data', function (data) { var messages = grunt.log.uncolor(data.toString()).split('\n'); messages.forEach(function (message) { if (message && message.indexOf('error ') > -1) { notify(message, 'stdout'); } }); }); } }); }) (module); 

然后你需要用一个require语句把它包含在你的Gruntfile.js中

 module.exports = function (grunt) { grunt.initConfig({ ... }); require('./tasks/lib/notify'); ... }; 

PS我已经把文件放在tasks/lib/notify.js ,但随意放置在别的地方。