27 lines
680 B
JavaScript
27 lines
680 B
JavaScript
'use strict';
|
|
|
|
function isBrokenPipeError(error) {
|
|
return error?.code === 'EPIPE';
|
|
}
|
|
|
|
function installOutputPipeGuards({
|
|
stdout = process.stdout,
|
|
stderr = process.stderr,
|
|
onBrokenPipe = () => {}
|
|
} = {}) {
|
|
const guardedStreams = [stdout, stderr].filter(Boolean);
|
|
const handlers = guardedStreams.map((stream) => {
|
|
const handler = (error) => {
|
|
if (!isBrokenPipeError(error)) throw error;
|
|
onBrokenPipe(error);
|
|
};
|
|
stream.on('error', handler);
|
|
return { stream, handler };
|
|
});
|
|
return () => {
|
|
for (const { stream, handler } of handlers) stream.off('error', handler);
|
|
};
|
|
}
|
|
|
|
module.exports = { installOutputPipeGuards, isBrokenPipeError };
|