or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# USB Library for Node.js

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: usb

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install usb`

10

11

## Core Imports

12

13

```typescript

14

// Main USB functionality

15

import { usb, getDeviceList, findByIds, findBySerialNumber } from 'usb';

16

17

// WebUSB compatibility

18

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

19

20

// Device and transfer classes

21

import { Device, Transfer, LibUSBException } from 'usb';

22

23

// Endpoint and interface classes

24

import { InEndpoint, OutEndpoint, Endpoint, Interface } from 'usb';

25

26

// Capability classes

27

import { Capability } from 'usb';

28

29

// Utility functions

30

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

31

32

// Type definitions

33

import type {

34

DeviceDescriptor,

35

ConfigDescriptor,

36

InterfaceDescriptor,

37

EndpointDescriptor,

38

BosDescriptor,

39

CapabilityDescriptor

40

} from 'usb';

41

42

// WebUSB type definitions

43

import type {

44

USBOptions,

45

USBDeviceRequestOptions,

46

USBDeviceFilter,

47

USBControlTransferParameters,

48

USBInTransferResult,

49

USBOutTransferResult,

50

USBConnectionEvent,

51

USBConfiguration,

52

USBDevice

53

} from 'usb';

54

```

55

56

For CommonJS:

57

```javascript

58

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

59

```

60

61

## Basic Usage

62

63

```typescript

64

import { getDeviceList, findByIds } from 'usb';

65

66

// List all USB devices

67

const devices = getDeviceList();

68

console.log(`Found ${devices.length} USB devices`);

69

70

// Find specific device by vendor/product ID

71

const device = findByIds(0x1234, 0x5678);

72

if (device) {

73

device.open();

74

console.log('Device opened successfully');

75

76

// Perform operations...

77

78

device.close();

79

}

80

```

81

82

## Architecture

83

84

The USB library provides two main APIs:

85

86

1. **Legacy USB API**: Direct access to libusb functionality with full control over devices, interfaces, and endpoints

87

2. **WebUSB API**: Browser-compatible API that wraps the legacy API for easier integration with web-based applications

88

89

Key components:

90

- **Device Management**: Discovery, opening, configuration of USB devices

91

- **Interface Control**: Claiming and managing device interfaces

92

- **Endpoint Communication**: Data transfer through IN/OUT endpoints

93

- **Event System**: Hotplug detection and device attach/detach events

94

- **Descriptor Access**: Reading device, configuration, interface, and endpoint descriptors

95

96

## Capabilities

97

98

### [Device Discovery and Management](./device-management.md)

99

100

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

101

102

```typescript { .api }

103

/**

104

* Get list of all attached USB devices

105

* @returns Array of Device objects

106

*/

107

function getDeviceList(): Device[];

108

109

/**

110

* Find device by vendor and product ID

111

* @param vid - Vendor ID

112

* @param pid - Product ID

113

* @returns Device or undefined if not found

114

*/

115

function findByIds(vid: number, pid: number): Device | undefined;

116

117

/**

118

* Find device by serial number

119

* @param serialNumber - Serial number string

120

* @returns Promise resolving to Device or undefined

121

*/

122

function findBySerialNumber(serialNumber: string): Promise<Device | undefined>;

123

124

interface Device {

125

busNumber: number;

126

deviceAddress: number;

127

portNumbers: number[];

128

deviceDescriptor: DeviceDescriptor;

129

interfaces?: Interface[];

130

timeout: number;

131

}

132

```

133

134

### [Device Communication](./device-communication.md)

135

136

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

137

138

```typescript { .api }

139

/**

140

* Extended Device class with communication methods

141

*/

142

interface ExtendedDevice extends Device {

143

/**

144

* Open device for communication

145

* @param defaultConfig - Whether to use default configuration

146

*/

147

open(defaultConfig?: boolean): void;

148

149

/**

150

* Close device

151

*/

152

close(): void;

153

154

/**

155

* Perform control transfer

156

* @param bmRequestType - Request type

157

* @param bRequest - Request

158

* @param wValue - Value

159

* @param wIndex - Index

160

* @param data_or_length - Data buffer or length for IN transfer

161

* @param callback - Completion callback

162

*/

163

controlTransfer(

164

bmRequestType: number,

165

bRequest: number,

166

wValue: number,

167

wIndex: number,

168

data_or_length: number | Buffer,

169

callback?: (error?: LibUSBException, data?: Buffer | number) => void

170

): Device;

171

}

172

```

173

174

### [Interface and Endpoint Management](./interfaces-endpoints.md)

175

176

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

177

178

```typescript { .api }

179

/**

180

* USB Interface for device communication

181

*/

182

interface Interface {

183

interfaceNumber: number;

184

altSetting: number;

185

descriptor: InterfaceDescriptor;

186

endpoints: Endpoint[];

187

188

/**

189

* Claim interface for exclusive use

190

*/

191

claim(): void;

192

193

/**

194

* Release interface

195

* @param closeEndpoints - Whether to stop endpoint streams

196

* @param callback - Completion callback

197

*/

198

release(closeEndpoints?: boolean, callback?: (error?: LibUSBException) => void): void;

199

200

/**

201

* Get endpoint by address

202

* @param addr - Endpoint address

203

*/

204

endpoint(addr: number): Endpoint | undefined;

205

}

206

207

/**

208

* Base endpoint class

209

*/

210

interface Endpoint {

211

address: number;

212

direction: 'in' | 'out';

213

transferType: number;

214

timeout: number;

215

descriptor: EndpointDescriptor;

216

}

217

```

218

219

### [Data Transfers](./data-transfers.md)

220

221

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

222

223

```typescript { .api }

224

/**

225

* IN endpoint for receiving data from device

226

*/

227

interface InEndpoint extends Endpoint {

228

direction: 'in';

229

pollActive: boolean;

230

231

/**

232

* Perform single transfer to read data

233

* @param length - Number of bytes to read

234

* @param callback - Completion callback

235

*/

236

transfer(length: number, callback: (error?: LibUSBException, data?: Buffer) => void): InEndpoint;

237

238

/**

239

* Start continuous polling for data

240

* @param nTransfers - Number of concurrent transfers

241

* @param transferSize - Size of each transfer

242

* @param callback - Transfer completion callback

243

*/

244

startPoll(nTransfers?: number, transferSize?: number, callback?: Function): Transfer[];

245

246

/**

247

* Stop polling

248

* @param callback - Completion callback

249

*/

250

stopPoll(callback?: () => void): void;

251

}

252

253

/**

254

* OUT endpoint for sending data to device

255

*/

256

interface OutEndpoint extends Endpoint {

257

direction: 'out';

258

259

/**

260

* Perform transfer to write data

261

* @param buffer - Data to write

262

* @param callback - Completion callback

263

*/

264

transfer(buffer: Buffer, callback?: (error?: LibUSBException, actual: number) => void): OutEndpoint;

265

}

266

```

267

268

### [Event Handling](./event-handling.md)

269

270

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

271

272

```typescript { .api }

273

/**

274

* USB event system

275

*/

276

interface DeviceEvents {

277

attach: Device;

278

detach: Device;

279

attachIds: { idVendor: number; idProduct: number };

280

detachIds: { idVendor: number; idProduct: number };

281

}

282

283

/**

284

* USB module extends EventEmitter

285

*/

286

interface USB extends EventEmitter {

287

pollHotplug: boolean;

288

pollHotplugDelay: number;

289

290

/**

291

* Add event listener

292

* @param event - Event name

293

* @param listener - Event handler

294

*/

295

on<K extends keyof DeviceEvents>(event: K, listener: (arg: DeviceEvents[K]) => void): void;

296

297

/**

298

* Remove event listener

299

* @param event - Event name

300

* @param listener - Event handler

301

*/

302

off<K extends keyof DeviceEvents>(event: K, listener: (arg: DeviceEvents[K]) => void): void;

303

}

304

```

305

306

### [WebUSB Compatibility](./webusb-api.md)

307

308

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

309

310

```typescript { .api }

311

/**

312

* WebUSB interface compatible with navigator.usb

313

*/

314

interface USB {

315

/**

316

* Request access to USB device

317

* @param options - Device filter options

318

* @returns Promise resolving to selected device

319

*/

320

requestDevice(options?: USBDeviceRequestOptions): Promise<USBDevice>;

321

322

/**

323

* Get previously authorized devices

324

* @returns Promise resolving to device array

325

*/

326

getDevices(): Promise<USBDevice[]>;

327

328

/**

329

* Connect event handler

330

*/

331

onconnect: ((ev: USBConnectionEvent) => void) | undefined;

332

333

/**

334

* Disconnect event handler

335

*/

336

ondisconnect: ((ev: USBConnectionEvent) => void) | undefined;

337

}

338

339

/**

340

* WebUSB Device interface

341

*/

342

interface USBDevice {

343

vendorId: number;

344

productId: number;

345

deviceClass: number;

346

manufacturerName?: string;

347

productName?: string;

348

serialNumber?: string;

349

configurations: USBConfiguration[];

350

351

/**

352

* Open device for communication

353

*/

354

open(): Promise<void>;

355

356

/**

357

* Close device

358

*/

359

close(): Promise<void>;

360

361

/**

362

* Claim interface

363

* @param interfaceNumber - Interface to claim

364

*/

365

claimInterface(interfaceNumber: number): Promise<void>;

366

}

367

```

368

369

### [Descriptors and Metadata](./descriptors.md)

370

371

Access USB descriptors to understand device capabilities and configuration.

372

373

```typescript { .api }

374

/**

375

* USB Device Descriptor

376

*/

377

interface DeviceDescriptor {

378

bLength: number;

379

bDescriptorType: number;

380

bcdUSB: number;

381

bDeviceClass: number;

382

bDeviceSubClass: number;

383

bDeviceProtocol: number;

384

bMaxPacketSize0: number;

385

idVendor: number;

386

idProduct: number;

387

bcdDevice: number;

388

iManufacturer: number;

389

iProduct: number;

390

iSerialNumber: number;

391

bNumConfigurations: number;

392

}

393

394

/**

395

* USB Configuration Descriptor

396

*/

397

interface ConfigDescriptor {

398

bLength: number;

399

bDescriptorType: number;

400

wTotalLength: number;

401

bNumInterfaces: number;

402

bConfigurationValue: number;

403

iConfiguration: number;

404

bmAttributes: number;

405

bMaxPower: number;

406

extra: Buffer;

407

interfaces: InterfaceDescriptor[][];

408

}

409

```

410

411

### [Constants and Error Handling](./constants-errors.md)

412

413

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

414

415

```typescript { .api }

416

/**

417

* LibUSB Exception class

418

*/

419

interface LibUSBException extends Error {

420

errno: number;

421

}

422

423

/**

424

* USB Class Constants

425

*/

426

const LIBUSB_CLASS_AUDIO: number;

427

const LIBUSB_CLASS_HID: number;

428

const LIBUSB_CLASS_MASS_STORAGE: number;

429

430

/**

431

* Transfer Type Constants

432

*/

433

const LIBUSB_TRANSFER_TYPE_CONTROL: number;

434

const LIBUSB_TRANSFER_TYPE_BULK: number;

435

const LIBUSB_TRANSFER_TYPE_INTERRUPT: number;

436

437

/**

438

* Error Constants

439

*/

440

const LIBUSB_ERROR_TIMEOUT: number;

441

const LIBUSB_ERROR_NO_DEVICE: number;

442

const LIBUSB_ERROR_ACCESS: number;

443

```