fixUtf8Stream.js 744 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. const {StringDecoder} = require('string_decoder');
  3. const {none, flushable} = require('../defs');
  4. const fixUtf8Stream = () => {
  5. const stringDecoder = new StringDecoder();
  6. let input = '';
  7. return flushable(chunk => {
  8. if (chunk === none) {
  9. const result = input + stringDecoder.end();
  10. input = '';
  11. return result;
  12. }
  13. if (typeof chunk == 'string') {
  14. if (!input) return chunk;
  15. const result = input + chunk;
  16. input = '';
  17. return result;
  18. }
  19. if (chunk instanceof Buffer) {
  20. const result = input + stringDecoder.write(chunk);
  21. input = '';
  22. return result;
  23. }
  24. throw new TypeError('Expected a string or a Buffer');
  25. });
  26. };
  27. module.exports = fixUtf8Stream;