UNPKG

aero-win-usb-detection

Version:

Listen to USB devices for attach/detach and get drive path and label (Windows only)

60 lines 2.64 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { usb } from "usb"; import EventEmitter from "events"; import edge from "edge-js"; import path from "path"; import { fileURLToPath } from "url"; export default class UsbEventsContorller extends EventEmitter { constructor() { super(); this.drivesCache = {}; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const rootPath = path.join(__dirname, "/RemovableUsbInfo.dll"); this.dll = edge.func(rootPath); } startListening() { return __awaiter(this, void 0, void 0, function* () { usb.on("attach", (device) => { console.log("attach"); var payload = { ProductId: device.deviceDescriptor.idProduct, VendorId: device.deviceDescriptor.idVendor, }; var _this = this; this.dll(payload, function (error, result) { if (error) { console.error(error); return; } if (result == null) return; var driveKey = `${device.deviceDescriptor.idProduct}_${device.deviceDescriptor.idVendor}`; _this.drivesCache[driveKey] = result; _this.emit("attach", result); }); }); usb.on("detach", (device) => { console.log("detach"); var driveKey = `${device.deviceDescriptor.idProduct}_${device.deviceDescriptor.idVendor}`; var result = this.drivesCache[driveKey]; if (result) { delete this.drivesCache[driveKey]; this.emit("detach", result); } }); }); } stopListening() { usb.removeAllListeners(); } } //# sourceMappingURL=UsbEventsContorller.js.map