Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Created February 19, 2024 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezzabuzaid/03f3e21c131dcc40ecd0e3778a8d8d5d to your computer and use it in GitHub Desktop.
Save ezzabuzaid/03f3e21c131dcc40ecd0e3778a8d8d5d to your computer and use it in GitHub Desktop.
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