notify.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. "use strict";
  2. var through = require('through2');
  3. var report = require('./report');
  4. var extra = require('./extra_api');
  5. var notifier = require('node-notifier');
  6. module.exports = function (options) {
  7. var reporter;
  8. var lastFile = null;
  9. options = options || {};
  10. var templateOptions = options.templateOptions || {};
  11. if (options.notifier) {
  12. reporter = options.notifier;
  13. } else {
  14. if (options.host || options.appName || options.port) {
  15. notifier = new notifier.Notification({
  16. host: options.host || 'localhost',
  17. appName: options.appName || 'gulp-notify',
  18. port: options.port || '23053'
  19. });
  20. }
  21. reporter = notifier.notify.bind(notifier);
  22. }
  23. function notify (file, enc, callback) {
  24. var stream = this;
  25. report(reporter, file, options, templateOptions, function (err) {
  26. logError(err, stream);
  27. if (options.emitError) {
  28. stream.push(file);
  29. return callback();
  30. }
  31. });
  32. if (!options.emitError) {
  33. stream.push(file);
  34. return callback();
  35. }
  36. }
  37. if (!options.onLast) {
  38. return through.obj(notify);
  39. }
  40. // Only send notification on the last file.
  41. return through.obj(function (file, enc, callback) {
  42. lastFile = file;
  43. this.push(file);
  44. callback();
  45. }, function (callback) {
  46. var stream = this;
  47. if (!lastFile) {
  48. return callback();
  49. }
  50. report(reporter, lastFile, options, templateOptions, function (err) {
  51. logError(err, stream);
  52. if (options.emitError) {
  53. return callback();
  54. }
  55. });
  56. lastFile = null; // reset
  57. if (!options.emitError) {
  58. return callback();
  59. }
  60. });
  61. function logError (err, stream) {
  62. if (!err) return;
  63. var isGrowl = notifier && notifier instanceof notifier.Growl;
  64. var isEcon = err.message.indexOf('ECONNREFUSED') !== -1;
  65. var dropMessage = isGrowl && isEcon;
  66. if (dropMessage) {
  67. return extra.logError({
  68. title: 'Info',
  69. message: 'No notification system installed.'
  70. });
  71. }
  72. if (options.emitError) return stream.emit('error', err);
  73. extra.logError({
  74. title: 'Error in notifier',
  75. message: err
  76. }, true);
  77. }
  78. };
  79. module.exports.on = function (event, fn) {
  80. if (!notifier) return;
  81. return notifier.on(event, function (notifyObject, options) {
  82. return fn(options);
  83. });
  84. };