-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparseStream.js
84 lines (59 loc) · 1.65 KB
/
parseStream.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
var util = require('util');
var Writable = require('stream').Writable;
var unflat = require('./lib/unflat.js');
var unbox = require('./lib/unbox.js');
/**
*
* @param options
* @constructor
*/
var ParseStream = function (endCallback) {
Writable.call(this, {objectMode: true});
this.endCallback = endCallback;
this.on('finish', this.onEnd.bind(this))
}
util.inherits(ParseStream, Writable);
ParseStream.prototype.boxes = [];
/**
*
* @param data
* @param enc
* @param done
*
* @private
*/
ParseStream.prototype._write = function(data, enc, done) {
if (this.boxFrag) {
var dataToConcat = data;
if (this.boxFrag.currentLength + dataToConcat.length > this.boxFrag.length ) {
var remainingBuffer = this.boxFrag.currentLength + data.length - this.boxFrag.length;
dataToConcat = data.slice(0, data.length - remainingBuffer);
var dataRemains = data.slice( data.length - remainingBuffer);
}
this.boxFrag.currentLength += dataToConcat.length;
// concat only what needed
this.boxFrag.data = Buffer.concat([this.boxFrag.data, dataToConcat]);
// remaining data passed to boxparser
if (this.boxFrag.currentLength === this.boxFrag.length) {
this.boxes.push(this.boxFrag);
this.boxFrag = null;
}
if (dataRemains && dataRemains.length > 0) {
this.parseBox(dataRemains);
}
done();
} else {
this.parseBox(data);
done();
}
};
ParseStream.prototype.parseBox = function (data) {
var boxFragment = unbox(data, 0, this.boxes.push.bind(this.boxes));
if (boxFragment) {
this.boxFrag = boxFragment;
}
}
ParseStream.prototype.onEnd = function () {
this.endCallback(null, unflat(this.boxes));
}
module.exports = ParseStream;