-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
40 lines (30 loc) · 887 Bytes
/
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
'use strict';
const {pipeline} = require('stream');
const cancel = new Error('Canceled.');
module.exports = function cancelablePipeline(...args) {
if (args.length === 0) {
throw new RangeError('Expected at least 1 argument, but got no arguments.');
}
const nonCallbackArgs = args;
const callback = typeof nonCallbackArgs[nonCallbackArgs.length - 1] === 'function' ?
nonCallbackArgs.pop() :
null;
const streams = Array.isArray(args[0]) ? args[0] : nonCallbackArgs;
const streamCount = streams.length;
if (streamCount < 2) {
throw new RangeError(`cancelable-pipeline requires more than 2 streams, but got ${streamCount}.`);
}
pipeline(streams, err => {
if (!callback) {
return;
}
if (err && err !== cancel) {
callback(err);
return;
}
callback();
});
return function cancelStreams() {
streams[streamCount - 1].emit('error', cancel);
};
};