-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (62 loc) · 2.32 KB
/
Copy pathindex.js
File metadata and controls
77 lines (62 loc) · 2.32 KB
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
'use strict';
module.exports = getStreamSequentalReader;
/**
*
* @param stream
* @returns {Function}
*/
function getStreamSequentalReader(stream) {
let eof = false;
let wasUnshifted = false;
return function (bytes) {
return new Promise((resolve, reject) => {
if (eof) {
resolve(null);
return;
}
var buf = new Buffer(0);
var onReadable = () => {
wasUnshifted = false;
var tmp = stream.read();
if (tmp !== null) {
var needBytes = bytes - buf.length;
if (tmp.length < needBytes) {
// we've read less bytes than we need or exactly the same amount as we need
buf = Buffer.concat([buf, tmp]);
} else {
// we've read more than we need
var firstChunk = tmp.slice(0, needBytes);
var secondChunk = tmp.slice(needBytes, tmp.length);
buf = Buffer.concat([buf, firstChunk]);
removeListeners();
if (secondChunk.length > 0) {
stream.unshift(secondChunk);
wasUnshifted = true;
}
resolve(buf);
}
}
// push out last chunk of data in case we're reading from stdin
stream.read(0);
};
var onEnd = () => {
eof = true;
removeListeners();
resolve(buf && buf.length > 0 ? buf : null);
};
var onError = (e) => {
return reject(e);
};
var removeListeners = () => {
stream.removeListener('readable', onReadable);
stream.removeListener('end', onEnd);
stream.removeListener('error', onError);
};
stream.on('readable', onReadable);
stream.on('end', onEnd);
stream.on('error', onError);
// emit readable event in case that internal buffer already contains data before the function was called
/* if (wasUnshifted) */ stream.emit('readable');
});
};
}