line-buffer.js 1.3 KB

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