-
Notifications
You must be signed in to change notification settings - Fork 28
/
transformStream.js
59 lines (52 loc) · 1.87 KB
/
transformStream.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
import {parse} from './tXml.js'
import through2 from 'through2';
export function transformStream(offset, parseOptions) {
if(!parseOptions) parseOptions = {};
if (typeof offset === 'string') {
offset = offset.length;
}
var position = offset || 0;
var data = '';
const stream = through2({ readableObjectMode: true }, function (chunk, enc, callback) {
data += chunk;
var lastPos = 0;
do {
position = data.indexOf('<', position) + 1;
if (!position) {
position = lastPos;
return callback();;
}
if (data[position] === '/') {
position = position + 1;
lastPos = position;
continue;
}
if (data[position] === '!' && data[position + 1] === '-' && data[position + 2] === '-') {
const commentEnd = data.indexOf('-->', position + 3);
if (commentEnd === -1) {
data = data.slice(lastPos);
position = 0;
return callback();;
}
if(parseOptions.keepComments){
this.push(data.substring(position-1, commentEnd+3));
}
position = commentEnd + 1;
lastPos = commentEnd;
continue;
}
var res = parse(data, {...parseOptions, pos: position - 1, parseNode: true, setPos: true });
position = res.pos;
//console.log(res, res.pos)
if (position > (data.length - 1) || position < lastPos) {
data = data.slice(lastPos);
position = 0;
return callback();;
} else {
this.push(res);
lastPos = position;
}
} while (1);
});
return stream;
}