Created
February 19, 2024 11:32
-
-
Save ezzabuzaid/03f3e21c131dcc40ecd0e3778a8d8d5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import internal, { PassThrough, Transform } from 'stream'; | |
export function concatStreams({ | |
streams, | |
delimiter, | |
}: { | |
delimiter?: string; | |
streams: (() => internal.Readable)[]; | |
}) { | |
const destination = new PassThrough({ objectMode: true }); | |
if (!Array.isArray(streams) || !streams.length) { | |
destination.end(); | |
console.log('No streams to concat'); | |
return destination; | |
} | |
const next = () => { | |
if (!streams.length) { | |
destination.end(); | |
return; | |
} | |
if (destination.destroyed || destination.closed) return; | |
const stream = streams.shift()!(); | |
if (delimiter) { | |
const delimiterTransform = new Transform({ | |
transform(chunk, encoding, callback) { | |
this.push(chunk); | |
callback(); | |
}, | |
flush(callback) { | |
if (streams.length) { | |
this.push(delimiter); | |
callback(); | |
} | |
}, | |
}); | |
stream.pipe(delimiterTransform).pipe(destination, { end: false }); | |
} else { | |
stream.pipe(destination, { end: false }); | |
} | |
stream.on('end', next); | |
stream.on('error', (error) => destination.emit('error', error)); | |
destination.once('close', () => { | |
if (!stream.destroyed) { | |
stream.destroy(); | |
} | |
}); | |
}; | |
next(); | |
return destination; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment