UNPKG

1.04 kBPlain TextView Raw
1import { Readable } from 'stream'
2import { CommonLogger } from '@naturalcycles/js-lib'
3
4export function pipelineClose(
5 name: string,
6 readableDownstream: Readable,
7 sourceReadable: Readable | undefined,
8 streamDone: Promise<void> | undefined,
9 logger: CommonLogger,
10): void {
11 readableDownstream.push(null) // this closes the stream, so downstream Readable will receive `end` and won't write anything
12
13 if (!sourceReadable) {
14 logger.warn(`${name} sourceReadable is not provided, readable stream will not be stopped`)
15 } else {
16 logger.log(`${name} is calling readable.unpipe() to pause the stream`)
17 sourceReadable.unpipe() // it is expected to pause the stream
18
19 if (!streamDone) {
20 logger.log(`${name} streamDone is not provided, will do readable.destroy right away`)
21 sourceReadable.destroy()
22 } else {
23 void streamDone.then(() => {
24 logger.log(`${name} streamDone, calling readable.destroy()`)
25 sourceReadable.destroy() // this throws ERR_STREAM_PREMATURE_CLOSE
26 })
27 }
28 }
29}