pipeline.js
This file
Path
lib/io/pipeline.js
53 lines · 1.5 KiB · JavaScript
Last changed by
Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import {finished} from 'node:stream/promises';import {isStandardStream} from '../utils/standard-stream.js';
// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams.// `onDestinationEnd` runs when the destination ends, before the source is aborted.export const pipeStreams = (source, destination, onDestinationEnd) => { source.pipe(destination); onSourceFinish(source, destination); onDestinationFinish(source, destination, onDestinationEnd);};
// `source.pipe(destination)` makes `destination` end when `source` ends.// But it does not propagate aborts or errors. This function does it.const onSourceFinish = async (source, destination) => { if (isStandardStream(source) || isStandardStream(destination)) { return; }
try { await finished(source, {cleanup: true, readable: true, writable: false}); } catch {}
endDestinationStream(destination);};
export const endDestinationStream = destination => { if (destination.writable) { destination.end(); }};
// We do the same thing in the other direction as well.const onDestinationFinish = async (source, destination, onDestinationEnd) => { if (isStandardStream(source) || isStandardStream(destination)) { return; }
try { await finished(destination, {cleanup: true, readable: false, writable: true}); } catch {}
if (onDestinationEnd !== undefined) { await onDestinationEnd(); }
abortSourceStream(source);};
export const abortSourceStream = source => { if (source.readable) { source.destroy(); }};