index.js 1008 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. var through = require('through2');
  3. var removeBom = require('remove-bom-buffer');
  4. var SafeBuffer = require('safe-buffer').Buffer;
  5. function removeBomStream() {
  6. var completed = false;
  7. var buffer = SafeBuffer.alloc(0);
  8. return through(onChunk, onFlush);
  9. function removeAndCleanup(data) {
  10. completed = true;
  11. buffer = null;
  12. return removeBom(data);
  13. }
  14. function onChunk(data, enc, cb) {
  15. if (completed) {
  16. return cb(null, data);
  17. }
  18. if (data.length >= 7) {
  19. return cb(null, removeAndCleanup(data));
  20. }
  21. var bufferLength = buffer.length;
  22. var chunkLength = data.length;
  23. var totalLength = bufferLength + chunkLength;
  24. buffer = SafeBuffer.concat([buffer, data], totalLength);
  25. if (totalLength >= 7) {
  26. return cb(null, removeAndCleanup(buffer));
  27. }
  28. cb();
  29. }
  30. function onFlush(cb) {
  31. if (completed || !buffer) {
  32. return cb();
  33. }
  34. cb(null, removeAndCleanup(buffer));
  35. }
  36. }
  37. module.exports = removeBomStream;