data-stream.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. 'use strict';
  2. const stream = require('stream');
  3. const Transform = stream.Transform;
  4. /**
  5. * Escapes dots in the beginning of lines. Ends the stream with <CR><LF>.<CR><LF>
  6. * Also makes sure that only <CR><LF> sequences are used for linebreaks
  7. *
  8. * @param {Object} options Stream options
  9. */
  10. class DataStream extends Transform {
  11. constructor(options) {
  12. super(options);
  13. // init Transform
  14. this.options = options || {};
  15. this._curLine = '';
  16. this.inByteCount = 0;
  17. this.outByteCount = 0;
  18. this.lastByte = false;
  19. }
  20. /**
  21. * Escapes dots
  22. */
  23. _transform(chunk, encoding, done) {
  24. let chunks = [];
  25. let chunklen = 0;
  26. let i,
  27. len,
  28. lastPos = 0;
  29. let buf;
  30. if (!chunk || !chunk.length) {
  31. return done();
  32. }
  33. if (typeof chunk === 'string') {
  34. chunk = Buffer.from(chunk);
  35. }
  36. this.inByteCount += chunk.length;
  37. for (i = 0, len = chunk.length; i < len; i++) {
  38. if (chunk[i] === 0x2e) {
  39. // .
  40. if ((i && chunk[i - 1] === 0x0a) || (!i && (!this.lastByte || this.lastByte === 0x0a))) {
  41. buf = chunk.slice(lastPos, i + 1);
  42. chunks.push(buf);
  43. chunks.push(Buffer.from('.'));
  44. chunklen += buf.length + 1;
  45. lastPos = i + 1;
  46. }
  47. } else if (chunk[i] === 0x0a) {
  48. // .
  49. if ((i && chunk[i - 1] !== 0x0d) || (!i && this.lastByte !== 0x0d)) {
  50. if (i > lastPos) {
  51. buf = chunk.slice(lastPos, i);
  52. chunks.push(buf);
  53. chunklen += buf.length + 2;
  54. } else {
  55. chunklen += 2;
  56. }
  57. chunks.push(Buffer.from('\r\n'));
  58. lastPos = i + 1;
  59. }
  60. }
  61. }
  62. if (chunklen) {
  63. // add last piece
  64. if (lastPos < chunk.length) {
  65. buf = chunk.slice(lastPos);
  66. chunks.push(buf);
  67. chunklen += buf.length;
  68. }
  69. this.outByteCount += chunklen;
  70. this.push(Buffer.concat(chunks, chunklen));
  71. } else {
  72. this.outByteCount += chunk.length;
  73. this.push(chunk);
  74. }
  75. this.lastByte = chunk[chunk.length - 1];
  76. done();
  77. }
  78. /**
  79. * Finalizes the stream with a dot on a single line
  80. */
  81. _flush(done) {
  82. let buf;
  83. if (this.lastByte === 0x0a) {
  84. buf = Buffer.from('.\r\n');
  85. } else if (this.lastByte === 0x0d) {
  86. buf = Buffer.from('\n.\r\n');
  87. } else {
  88. buf = Buffer.from('\r\n.\r\n');
  89. }
  90. this.outByteCount += buf.length;
  91. this.push(buf);
  92. done();
  93. }
  94. }
  95. module.exports = DataStream;