or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

constants-errors.mddata-transfers.mddescriptors.mddevice-communication.mddevice-management.mdevent-handling.mdindex.mdinterfaces-endpoints.mdwebusb-api.md
tile.json

tessl/npm-usb

Cross-platform Node.js library for USB device communication with both legacy and WebUSB-compatible APIs.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/usb@2.16.x

To install, run

npx @tessl/cli install tessl/npm-usb@2.16.0

index.mddocs/

USB Library for Node.js

A comprehensive cross-platform Node.js library for communicating with USB devices. Provides both a legacy USB API for low-level device access and a WebUSB-compatible API that mimics the browser's navigator.usb interface. Built on libusb, it enables direct hardware communication including device enumeration, control transfers, bulk transfers, interrupt transfers, and hotplug event monitoring.

Package Information

  • Package Name: usb
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install usb

Core Imports

// Main USB functionality
import { usb, getDeviceList, findByIds, findBySerialNumber } from 'usb';

// WebUSB compatibility
import { webusb, getWebUsb, WebUSB, WebUSBDevice } from 'usb';

// Device and transfer classes
import { Device, Transfer, LibUSBException } from 'usb';

// Endpoint and interface classes
import { InEndpoint, OutEndpoint, Endpoint, Interface } from 'usb';

// Capability classes
import { Capability } from 'usb';

// Utility functions
import { setDebugLevel, useUsbDkBackend, refHotplugEvents, unrefHotplugEvents } from 'usb';

// Type definitions
import type { 
  DeviceDescriptor, 
  ConfigDescriptor, 
  InterfaceDescriptor, 
  EndpointDescriptor,
  BosDescriptor,
  CapabilityDescriptor
} from 'usb';

// WebUSB type definitions
import type {
  USBOptions,
  USBDeviceRequestOptions,
  USBDeviceFilter,
  USBControlTransferParameters,
  USBInTransferResult,
  USBOutTransferResult,
  USBConnectionEvent,
  USBConfiguration,
  USBDevice
} from 'usb';

For CommonJS:

const { usb, getDeviceList, findByIds, webusb } = require('usb');

Basic Usage

import { getDeviceList, findByIds } from 'usb';

// List all USB devices
const devices = getDeviceList();
console.log(`Found ${devices.length} USB devices`);

// Find specific device by vendor/product ID
const device = findByIds(0x1234, 0x5678);
if (device) {
  device.open();
  console.log('Device opened successfully');
  
  // Perform operations...
  
  device.close();
}

Architecture

The USB library provides two main APIs:

  1. Legacy USB API: Direct access to libusb functionality with full control over devices, interfaces, and endpoints
  2. WebUSB API: Browser-compatible API that wraps the legacy API for easier integration with web-based applications

Key components:

  • Device Management: Discovery, opening, configuration of USB devices
  • Interface Control: Claiming and managing device interfaces
  • Endpoint Communication: Data transfer through IN/OUT endpoints
  • Event System: Hotplug detection and device attach/detach events
  • Descriptor Access: Reading device, configuration, interface, and endpoint descriptors

Capabilities

Device Discovery and Management

Find, enumerate, and manage USB devices on the system.

/**
 * Get list of all attached USB devices
 * @returns Array of Device objects
 */
function getDeviceList(): Device[];

/**
 * Find device by vendor and product ID
 * @param vid - Vendor ID
 * @param pid - Product ID
 * @returns Device or undefined if not found
 */
function findByIds(vid: number, pid: number): Device | undefined;

/**
 * Find device by serial number
 * @param serialNumber - Serial number string
 * @returns Promise resolving to Device or undefined
 */
function findBySerialNumber(serialNumber: string): Promise<Device | undefined>;

interface Device {
  busNumber: number;
  deviceAddress: number;
  portNumbers: number[];
  deviceDescriptor: DeviceDescriptor;
  interfaces?: Interface[];
  timeout: number;
}

Device Communication

Open devices and perform control transfers for configuration and data exchange.

/**
 * Extended Device class with communication methods
 */
interface ExtendedDevice extends Device {
  /**
   * Open device for communication
   * @param defaultConfig - Whether to use default configuration
   */
  open(defaultConfig?: boolean): void;
  
  /**
   * Close device
   */
  close(): void;
  
  /**
   * Perform control transfer
   * @param bmRequestType - Request type
   * @param bRequest - Request
   * @param wValue - Value
   * @param wIndex - Index
   * @param data_or_length - Data buffer or length for IN transfer
   * @param callback - Completion callback
   */
  controlTransfer(
    bmRequestType: number,
    bRequest: number, 
    wValue: number,
    wIndex: number,
    data_or_length: number | Buffer,
    callback?: (error?: LibUSBException, data?: Buffer | number) => void
  ): Device;
}

Interface and Endpoint Management

Claim interfaces and manage data endpoints for bulk and interrupt transfers.

/**
 * USB Interface for device communication
 */
interface Interface {
  interfaceNumber: number;
  altSetting: number;
  descriptor: InterfaceDescriptor;
  endpoints: Endpoint[];
  
  /**
   * Claim interface for exclusive use
   */
  claim(): void;
  
  /**
   * Release interface
   * @param closeEndpoints - Whether to stop endpoint streams
   * @param callback - Completion callback
   */
  release(closeEndpoints?: boolean, callback?: (error?: LibUSBException) => void): void;
  
  /**
   * Get endpoint by address
   * @param addr - Endpoint address
   */
  endpoint(addr: number): Endpoint | undefined;
}

/**
 * Base endpoint class
 */
interface Endpoint {
  address: number;
  direction: 'in' | 'out';
  transferType: number;
  timeout: number;
  descriptor: EndpointDescriptor;
}

Data Transfers

Perform bulk, interrupt, and isochronous data transfers with endpoints.

/**
 * IN endpoint for receiving data from device
 */
interface InEndpoint extends Endpoint {
  direction: 'in';
  pollActive: boolean;
  
  /**
   * Perform single transfer to read data
   * @param length - Number of bytes to read
   * @param callback - Completion callback
   */
  transfer(length: number, callback: (error?: LibUSBException, data?: Buffer) => void): InEndpoint;
  
  /**
   * Start continuous polling for data
   * @param nTransfers - Number of concurrent transfers
   * @param transferSize - Size of each transfer
   * @param callback - Transfer completion callback
   */
  startPoll(nTransfers?: number, transferSize?: number, callback?: Function): Transfer[];
  
  /**
   * Stop polling
   * @param callback - Completion callback
   */
  stopPoll(callback?: () => void): void;
}

/**
 * OUT endpoint for sending data to device
 */
interface OutEndpoint extends Endpoint {
  direction: 'out';
  
  /**
   * Perform transfer to write data
   * @param buffer - Data to write
   * @param callback - Completion callback
   */
  transfer(buffer: Buffer, callback?: (error?: LibUSBException, actual: number) => void): OutEndpoint;
}

Event Handling

Monitor USB device attach/detach events and handle hotplug scenarios.

/**
 * USB event system
 */
interface DeviceEvents {
  attach: Device;
  detach: Device;
  attachIds: { idVendor: number; idProduct: number };
  detachIds: { idVendor: number; idProduct: number };
}

/**
 * USB module extends EventEmitter
 */
interface USB extends EventEmitter {
  pollHotplug: boolean;
  pollHotplugDelay: number;
  
  /**
   * Add event listener
   * @param event - Event name
   * @param listener - Event handler
   */
  on<K extends keyof DeviceEvents>(event: K, listener: (arg: DeviceEvents[K]) => void): void;
  
  /**
   * Remove event listener
   * @param event - Event name  
   * @param listener - Event handler
   */
  off<K extends keyof DeviceEvents>(event: K, listener: (arg: DeviceEvents[K]) => void): void;
}

WebUSB Compatibility

Browser-compatible WebUSB API for cross-platform USB device access.

/**
 * WebUSB interface compatible with navigator.usb
 */
interface USB {
  /**
   * Request access to USB device
   * @param options - Device filter options
   * @returns Promise resolving to selected device
   */
  requestDevice(options?: USBDeviceRequestOptions): Promise<USBDevice>;
  
  /**
   * Get previously authorized devices
   * @returns Promise resolving to device array
   */
  getDevices(): Promise<USBDevice[]>;
  
  /**
   * Connect event handler
   */
  onconnect: ((ev: USBConnectionEvent) => void) | undefined;
  
  /**
   * Disconnect event handler  
   */
  ondisconnect: ((ev: USBConnectionEvent) => void) | undefined;
}

/**
 * WebUSB Device interface
 */
interface USBDevice {
  vendorId: number;
  productId: number;
  deviceClass: number;
  manufacturerName?: string;
  productName?: string;
  serialNumber?: string;
  configurations: USBConfiguration[];
  
  /**
   * Open device for communication
   */
  open(): Promise<void>;
  
  /**
   * Close device
   */
  close(): Promise<void>;
  
  /**
   * Claim interface
   * @param interfaceNumber - Interface to claim
   */
  claimInterface(interfaceNumber: number): Promise<void>;
}

Descriptors and Metadata

Access USB descriptors to understand device capabilities and configuration.

/**
 * USB Device Descriptor
 */
interface DeviceDescriptor {
  bLength: number;
  bDescriptorType: number;
  bcdUSB: number;
  bDeviceClass: number;
  bDeviceSubClass: number;
  bDeviceProtocol: number;
  bMaxPacketSize0: number;
  idVendor: number;
  idProduct: number;
  bcdDevice: number;
  iManufacturer: number;
  iProduct: number;
  iSerialNumber: number;
  bNumConfigurations: number;
}

/**
 * USB Configuration Descriptor
 */
interface ConfigDescriptor {
  bLength: number;
  bDescriptorType: number;
  wTotalLength: number;
  bNumInterfaces: number;
  bConfigurationValue: number;
  iConfiguration: number;
  bmAttributes: number;  
  bMaxPower: number;
  extra: Buffer;
  interfaces: InterfaceDescriptor[][];
}

Constants and Error Handling

USB constants, error codes, and exception handling for robust applications.

/**
 * LibUSB Exception class
 */
interface LibUSBException extends Error {
  errno: number;
}

/**
 * USB Class Constants
 */
const LIBUSB_CLASS_AUDIO: number;
const LIBUSB_CLASS_HID: number;
const LIBUSB_CLASS_MASS_STORAGE: number;

/**
 * Transfer Type Constants  
 */
const LIBUSB_TRANSFER_TYPE_CONTROL: number;
const LIBUSB_TRANSFER_TYPE_BULK: number;
const LIBUSB_TRANSFER_TYPE_INTERRUPT: number;

/**
 * Error Constants
 */
const LIBUSB_ERROR_TIMEOUT: number;
const LIBUSB_ERROR_NO_DEVICE: number;
const LIBUSB_ERROR_ACCESS: number;