-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
streams.js
executable file
·62 lines (40 loc) · 1.29 KB
/
streams.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
'use strict';
const Stream = require('stream');
const Boom = require('@hapi/boom');
const Teamwork = require('@hapi/teamwork');
const internals = {
team: Symbol('team')
};
exports.isStream = function (stream) {
const isReadableStream = stream instanceof Stream.Readable;
if (!isReadableStream &&
typeof stream?.pipe === 'function') {
throw Boom.badImplementation('Cannot reply with a stream-like object that is not an instance of Stream.Readable');
}
if (!isReadableStream) {
return false;
}
if (stream.readableObjectMode) {
throw Boom.badImplementation('Cannot reply with stream in object mode');
}
return true;
};
exports.drain = function (stream) {
const team = new Teamwork.Team();
stream[internals.team] = team;
stream.on('readable', internals.read);
stream.on('error', internals.end);
stream.on('end', internals.end);
stream.on('close', internals.end);
return team.work;
};
internals.read = function () {
while (this.read()) { }
};
internals.end = function () {
this.removeListener('readable', internals.read);
this.removeListener('error', internals.end);
this.removeListener('end', internals.end);
this.removeListener('close', internals.end);
this[internals.team].attend();
};