File: index.js

package info (click to toggle)
node-vinyl-fs 3.0.3-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 1,884 kB
  • sloc: makefile: 43; sh: 43
file content (51 lines) | stat: -rw-r--r-- 1,008 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict';

var through = require('through2');
var removeBom = require('remove-bom-buffer');
var SafeBuffer = require('safe-buffer').Buffer;

function removeBomStream() {
  var completed = false;
  var buffer = SafeBuffer.alloc(0);

  return through(onChunk, onFlush);

  function removeAndCleanup(data) {
    completed = true;

    buffer = null;

    return removeBom(data);
  }

  function onChunk(data, enc, cb) {
    if (completed) {
      return cb(null, data);
    }

    if (data.length >= 7) {
      return cb(null, removeAndCleanup(data));
    }

    var bufferLength = buffer.length;
    var chunkLength = data.length;
    var totalLength = bufferLength + chunkLength;

    buffer = SafeBuffer.concat([buffer, data], totalLength);

    if (totalLength >= 7) {
      return cb(null, removeAndCleanup(buffer));
    }
    cb();
  }

  function onFlush(cb) {
    if (completed || !buffer) {
      return cb();
    }

    cb(null, removeAndCleanup(buffer));
  }
}

module.exports = removeBomStream;