Repository navigation
Expand file tree
/
Copy pathcreateSafeReadStream.mts
More file actions
55 lines (51 loc) · 1.79 KB
/
Copy pathcreateSafeReadStream.mts
File metadata and controls
55 lines (51 loc) · 1.79 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
import EventEmitter from 'node:events';
import type { Readable } from 'node:stream';
export function createSafeReadStream<S extends Readable, O>(
handle: {
createReadStream(options: O): S;
close?: () => Promise<void>;
},
options: O & {
start?: number | undefined;
end?: number | undefined;
autoClose?: boolean | undefined;
},
): S {
if (!(handle instanceof EventEmitter)) {
return handle.createReadStream(options);
}
if (options.end !== undefined && options.end < (options.start ?? 0)) {
throw new RangeError('invalid byte range');
}
// this helper is a workaround for https://github.com/nodejs/node/issues/64214
const wrappedHandle =
handle.close && options.autoClose === false
? new Proxy(handle, {
// stream must be destroyed on end, but will call handler.close, which we do not want.
// swap out handler.close for the stream to prevent this
get: (target, p, ...rest) =>
p === 'close' ? () => Promise.resolve() : Reflect.get(target, p, ...rest),
})
: handle;
const before = handle.listeners('close').length;
const stream = wrappedHandle.createReadStream(options);
const after = handle.listeners('close');
const listener = after.length > before ? (after[after.length - 1] as () => void) : undefined;
const onEnd = () => {
if (listener) {
// the close listener is not removed by Node.js, so we must remove it manually
handle.off('close', listener);
}
// if we do not call destroy on the stream, the eventual call to handler.close will hang
stream.destroy();
stream.off('end', onEnd);
stream.off('error', onError);
};
const onError = () => {
handle.close?.();
onEnd();
};
stream.once('end', onEnd);
stream.once('error', onError);
return stream;
}