stream.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. var path = require("path");
  3. var micromatch = require("micromatch");
  4. var utils = require("./public-utils");
  5. /**
  6. * @param emitter
  7. * @returns {Function}
  8. */
  9. module.exports = function (emitter) {
  10. /**
  11. * Return a transform/through stream that listens to file
  12. * paths and fires internal Browsersync events.
  13. * @param {{once: boolean, match: string|array}} [opts]
  14. * @returns {Stream.Transform}
  15. */
  16. function browserSyncThroughStream(opts) {
  17. opts = opts || {};
  18. var emitted = false;
  19. var Transform = require("stream").Transform;
  20. var reload = new Transform({ objectMode: true });
  21. var changed = [];
  22. reload._transform = function (file, encoding, next) {
  23. var stream = this;
  24. /**
  25. * End is always called to send the current file down
  26. * stream. Browsersync never acts upon a stream,
  27. * we only `listen` to it.
  28. */
  29. function end() {
  30. stream.push(file); // always send the file down-stream
  31. next();
  32. }
  33. /**
  34. * If {match: <pattern>} was provided, test the
  35. * current filepath against it
  36. */
  37. if (opts.match) {
  38. if (!micromatch(file.path, opts.match, { dot: true }).length) {
  39. return end();
  40. }
  41. }
  42. /**
  43. * if {once: true} provided, emit the reload event for the
  44. * first file only
  45. */
  46. if (opts.once === true && !emitted) {
  47. utils.emitBrowserReload(emitter);
  48. emitted = true;
  49. }
  50. else {
  51. // handle multiple
  52. if (opts.once === true && emitted) {
  53. }
  54. else {
  55. if (file.path) {
  56. emitted = true;
  57. utils.emitChangeEvent(emitter, file.path, false);
  58. changed.push(path.basename(file.path));
  59. }
  60. }
  61. }
  62. end();
  63. };
  64. /**
  65. * When this current operation has finished, emit the
  66. * steam:changed event so that any loggers can pick up it
  67. * @param next
  68. * @private
  69. */
  70. reload._flush = function (next) {
  71. if (changed.length) {
  72. utils.emitStreamChangedEvent(emitter, changed);
  73. }
  74. next();
  75. };
  76. return reload;
  77. }
  78. return browserSyncThroughStream;
  79. };
  80. //# sourceMappingURL=stream.js.map