-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
121 lines (103 loc) · 2.33 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**!
* co-readable - index.js
*
* Copyright(c) node-modules and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <[email protected]> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
const destroy = require('destroy');
const debug = require('debug')('co-readable');
module.exports = readable;
module.exports.readAll = readAll;
function readable(stream) {
let error = null;
let closed = false;
stream.on('error', onerror);
stream.on('close', onclose);
function onerror(err) {
debug('stream error: %s', err);
error = err;
}
function onclose() {
debug('stream close');
closed = true;
}
function cleanup() {
destroy(stream);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
}
return function* read(size) {
if (error) {
cleanup();
throw error;
}
if (closed) {
cleanup();
return;
}
const buf = stream.read(size);
if (buf) {
return buf;
}
// wait for next readable and try again
const result = yield any(stream, ['readable', 'end', 'error', 'close']);
debug('got stream %s', result.event);
if (result.event === 'end' || result.event === 'close') {
cleanup();
return;
}
if (result.event === 'error') {
cleanup();
throw result.data;
}
// got readable event
return yield read(size);
};
}
function* readAll(stream) {
const read = readable(stream);
const buffers = [];
let buf;
let size = 0;
while (buf = yield read()) {
buffers.push(buf);
size += buf.length;
}
return Buffer.concat(buffers, size);
}
function any(stream, events) {
return function (done) {
const listeners = [];
for (let i = 0; i < events.length; i++) {
let event = events[i];
listeners.push({
event: event,
fn: onEvent.bind(null, event)
});
}
function onEvent(event, data) {
cleanup();
done(null, {
event: event,
data: data
});
}
function cleanup() {
for (let i = 0; i < listeners.length; i++) {
let listener = listeners[i];
stream.removeListener(listener.event, listener.fn);
}
}
for (let i = 0; i < listeners.length; i++) {
let listener = listeners[i];
stream.on(listener.event, listener.fn);
}
};
}