lsusb lists all attached USB devices with their vendor:product IDs. This post shows a minimal TypeScript class that parses lsusb output and reports whether a specific device — e.g. a required WiFi dongle, license dongle or serial adapter — is still connected.
USBDevice.ts
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
export type CheckStatus = "ok" | "warning" | "error";
export interface CheckResult {
status: CheckStatus;
msg: string;
}
export interface USBDeviceCheckerConfig {
usbid?: string;
}
/**
* Check that a USB device with the given vendor:product ID is present, via lsusb.
*/
export class USBDeviceChecker {
private readonly expectedDevice: string;
constructor(config: USBDeviceCheckerConfig = {}) {
if (!config.usbid) {
throw new Error("USBDeviceChecker requires config.usbid, e.g. {usbid: '046d:c52b'}");
}
this.expectedDevice = config.usbid.toLowerCase();
}
async check(): Promise<CheckResult> {
let stdout: string;
try {
({ stdout } = await execFileAsync("lsusb"));
} catch (error: any) {
const code = error?.code;
if (code === 127 || code === "ENOENT") {
return { status: "error", msg: "lsusb command not found" };
}
return { status: "error", msg: `lsusb failed: ${error?.message ?? error}` };
}
// Line example: Bus 001 Device 004: ID 046d:c52b Logitech, Inc. Unifying Receiver
const findUSBIDs = /ID\s+([0-9a-f]{4}:[0-9a-f]{4})\s+([^\n]+)/gi;
let match: RegExpExecArray | null;
while ((match = findUSBIDs.exec(stdout)) !== null) {
if (match[1].toLowerCase() === this.expectedDevice) {
return { status: "ok", msg: `Found USB device ${this.expectedDevice}: ${match[2]}` };
}
}
return { status: "error", msg: `USB device ${this.expectedDevice} not found` };
}
}lsusb is part of the usbutils package. Find the ID of your device by running lsusb once and copying the ID xxxx:xxxx field.
Usage example
example.ts
import { USBDeviceChecker } from "./USBDevice.ts";
console.log(await new USBDeviceChecker({ usbid: "046d:0891" }).check());
// { status: 'ok', msg: 'Found USB device 046d:0891: Logitech, Inc. ...' }
console.log(await new USBDeviceChecker({ usbid: "ffff:ffff" }).check());
// { status: 'error', msg: 'USB device ffff:ffff not found' }
This is handy to monitor devices that occasionally drop off the bus — for example a 3D printer USB connection or a cellular modem — and trigger an alert or a reboot when the device disappears.
Check out similar posts by category:
TypeScript Linux Monitoring
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow