You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.0 KiB
JavaScript

"use strict";
const debug = require("debug")("promistream:from-node-stream:readable:attach-handlers");
const objectID = require("../object-id");
module.exports = function attachReadableStreamHandlers({ stream, onClose, onError, onData }) {
function detachEventHandlers() {
debug(`[#${objectID(stream)}] Detaching event handlers`);
stream.removeListener("end", onCloseWrapper);
stream.removeListener("close", onCloseWrapper);
stream.removeListener("error", onErrorWrapper);
stream.removeListener("data", onData);
}
function attachEventHandlers() {
debug(`[#${objectID(stream)}] Attaching event handlers`);
stream.on("end", onCloseWrapper);
stream.on("close", onCloseWrapper);
stream.on("error", onErrorWrapper);
stream.on("data", onData);
}
function onCloseWrapper() {
debug(`[#${objectID(stream)}] onCloseWrapper called`);
onClose();
detachEventHandlers();
}
function onErrorWrapper(error) {
debug(`[#${objectID(stream)}] onErrorWrapper called`);
onError(error);
detachEventHandlers();
}
attachEventHandlers();
};