Utf8Stream.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. const {Transform} = require('stream');
  3. const {StringDecoder} = require('string_decoder');
  4. class Utf8Stream extends Transform {
  5. constructor(options) {
  6. super(Object.assign({}, options, {writableObjectMode: false}));
  7. this._buffer = '';
  8. }
  9. _transform(chunk, encoding, callback) {
  10. if (typeof chunk == 'string') {
  11. this._transform = this._transformString;
  12. } else {
  13. this._stringDecoder = new StringDecoder();
  14. this._transform = this._transformBuffer;
  15. }
  16. this._transform(chunk, encoding, callback);
  17. }
  18. _transformBuffer(chunk, _, callback) {
  19. this._buffer += this._stringDecoder.write(chunk);
  20. this._processBuffer(callback);
  21. }
  22. _transformString(chunk, _, callback) {
  23. this._buffer += chunk.toString();
  24. this._processBuffer(callback);
  25. }
  26. _processBuffer(callback) {
  27. if (this._buffer) {
  28. this.push(this._buffer, 'utf8');
  29. this._buffer = '';
  30. }
  31. callback(null);
  32. }
  33. _flushInput() {
  34. // meant to be called from _flush()
  35. if (this._stringDecoder) {
  36. this._buffer += this._stringDecoder.end();
  37. }
  38. }
  39. _flush(callback) {
  40. this._flushInput();
  41. this._processBuffer(callback);
  42. }
  43. }
  44. module.exports = Utf8Stream;