line-buffer.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. const {
  3. EventEmitter
  4. } = require('events');
  5. class LineBuffer extends EventEmitter {
  6. constructor(options) {
  7. super();
  8. this.encoding = options.encoding;
  9. this.buffer = null;
  10. // part of cork/uncork
  11. this.corked = false;
  12. this.queue = [];
  13. }
  14. // Events:
  15. // line: here is a line
  16. // done: all lines emitted
  17. write(chunk) {
  18. // find line or lines in chunk and emit them if not corked
  19. // or queue them if corked
  20. const data = this.buffer ? this.buffer + chunk : chunk;
  21. const lines = data.split(/\r?\n/g);
  22. // save the last line
  23. this.buffer = lines.pop();
  24. lines.forEach(function (line) {
  25. if (this.corked) {
  26. this.queue.push(line);
  27. } else {
  28. this.emit('line', line);
  29. }
  30. });
  31. return !this.corked;
  32. }
  33. cork() {
  34. this.corked = true;
  35. }
  36. uncork() {
  37. this.corked = false;
  38. this._flush();
  39. // tell the source I'm ready again
  40. this.emit('drain');
  41. }
  42. setDefaultEncoding() {
  43. // ?
  44. }
  45. end() {
  46. if (this.buffer) {
  47. this.emit('line', this.buffer);
  48. this.buffer = null;
  49. }
  50. this.emit('done');
  51. }
  52. _flush() {
  53. if (!this.corked) {
  54. this.queue.forEach(line => {
  55. this.emit('line', line);
  56. });
  57. this.queue = [];
  58. }
  59. }
  60. }
  61. module.exports = LineBuffer;
  62. //# sourceMappingURL=line-buffer.js.map