node-escpos / driver

🖨️ ESC/POS Printer driver for Node.js.
Other
317 stars 32 forks source link

USB close function removes all usb detach listeners #50

Closed dschweinbenz closed 1 year ago

dschweinbenz commented 1 year ago

The close function of the usb adapter removes all detach listeners from the USB event emitter when the close function of a printer is called. That's a really bad practice as all listeners are removed from the event even those which are created in other packages or libraries.

 close(callback?: ((error: Error | null) => void) | undefined): this {
    if (!this.device) callback?.(new Error("Device not found"));
    try {
      this.device?.close();
      usb.removeAllListeners("detach");

As i am also listening for the usb.on('detach') event my code gets broken after a device close() was called... The detach event is used to remove the active printer if its linked device is detached:

usb.on("detach", (device) => {
      if (device === self.device) {
        self.emit("detach", device);
        self.emit("disconnect", device);
        self.device = null;
      }
    });

Expected behaviour: Only the single listener from this library should be removed if the close function is called