last-newline.js 670 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. const Transform = require('stream').Transform;
  3. class LastNewline extends Transform {
  4. constructor() {
  5. super();
  6. this.lastByte = false;
  7. }
  8. _transform(chunk, encoding, done) {
  9. if (chunk.length) {
  10. this.lastByte = chunk[chunk.length - 1];
  11. }
  12. this.push(chunk);
  13. done();
  14. }
  15. _flush(done) {
  16. if (this.lastByte === 0x0a) {
  17. return done();
  18. }
  19. if (this.lastByte === 0x0d) {
  20. this.push(Buffer.from('\n'));
  21. return done();
  22. }
  23. this.push(Buffer.from('\r\n'));
  24. return done();
  25. }
  26. }
  27. module.exports = LastNewline;