blob: 93501f197e3a28c04eac2b073d9e8066a578282c [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var through = require('through2');
4var removeBom = require('remove-bom-buffer');
5var SafeBuffer = require('safe-buffer').Buffer;
6
7function removeBomStream() {
8 var completed = false;
9 var buffer = SafeBuffer.alloc(0);
10
11 return through(onChunk, onFlush);
12
13 function removeAndCleanup(data) {
14 completed = true;
15
16 buffer = null;
17
18 return removeBom(data);
19 }
20
21 function onChunk(data, enc, cb) {
22 if (completed) {
23 return cb(null, data);
24 }
25
26 if (data.length >= 7) {
27 return cb(null, removeAndCleanup(data));
28 }
29
30 var bufferLength = buffer.length;
31 var chunkLength = data.length;
32 var totalLength = bufferLength + chunkLength;
33
34 buffer = SafeBuffer.concat([buffer, data], totalLength);
35
36 if (totalLength >= 7) {
37 return cb(null, removeAndCleanup(buffer));
38 }
39 cb();
40 }
41
42 function onFlush(cb) {
43 if (completed || !buffer) {
44 return cb();
45 }
46
47 cb(null, removeAndCleanup(buffer));
48 }
49}
50
51module.exports = removeBomStream;