escpos-ts API - v1.0.0
    Preparing search index...

    Class Usb

    USB printer implementation.

    Communicates with an ESC/POS printer over USB using the usb npm package (libusb bindings). Finds the device by Vendor/Product ID, claims the first matching interface, and writes to the first bulk-OUT endpoint.

    const printer = new Usb({ vendorId: 0x04b8, productId: 0x0202 });
    await printer.open();
    printer.textln('Hello, World!');
    printer.cut();
    await printer.close();

    1.0.0

    Hierarchy (View Summary)

    Index

    Constructors

    • Create a new USB printer instance.

      Parameters

      • config: UsbConfig

        USB configuration options

        Configuration options for the Usb printer.

        • Optionalinterface?: number

          USB interface number to claim (default: 0). Most ESC/POS printers expose a single printer interface at index 0.

        • productId: number

          USB Product ID (e.g. 0x0202 for Epson TM-T88IV)

        • OptionalprofileName?: string

          Printer profile name to use (default: 'default')

        • vendorId: number

          USB Vendor ID (e.g. 0x04b8 for Epson)

      Returns Usb

      1.0.0

    Properties

    Methods

    • Write raw bytes to the USB bulk-OUT endpoint.

      This is the low-level method called by all higher-level Escpos methods. The transfer is fire-and-forget (callback-based), matching how most POS printers operate — they accept data as fast as the host can send it.

      Parameters

      • data: Buffer

        Buffer containing ESC/POS command bytes to send

      Returns void

      if the device has not been opened

      1.0.0

    • Print a hardware barcode.

      Sends the appropriate GS k sequence for the requested barcode type and function type. Supports all types defined in BARCODE_TYPES (UPC-A, UPC-E, EAN8, EAN13, CODE39, ITF, NW7/CODABAR, CODE93, CODE128, and GS1 variants for Function Type B).

      Parameters

      • code: string

        Barcode data string.

      • bc: string

        Barcode type name (e.g. 'CODE128', 'EAN13'). Names are normalised (non-alphanumeric removed, uppercased) before lookup.

      • opts: BarcodeOptions = {}

        Optional barcode appearance settings; see BarcodeOptions.

      Returns void

      BarcodeTypeError if the type is unrecognised or unsupported.

      BarcodeCodeError if code fails format validation and opts.check is true (default).

      BarcodeSizeError if height or width are out of range.

      printer.barcode('012345678905', 'EAN13', { pos: 'BELOW', height: 80 });
      printer.barcode('{B12345678', 'CODE128', { functionType: 'B' });

      1.0.0

    • Print a word-wrapped text block.

      Wraps txt at word boundaries to fit within the column width of the selected font, as reported by the active printer profile.

      Parameters

      • txt: string

        UTF-8 string to wrap and print.

      • font: FontName = 'a'

        Font to use for column-width lookup ('a' or 'b'; default: 'a').

      • Optionalcolumns: number

        Override column count (uses profile value if omitted).

      Returns void

      1.0.0

    • Cut the paper.

      Feeds 6 lines before cutting unless feed is false. Falls back to a full cut when the profile does not support partial cuts, and vice versa.

      Parameters

      • mode: "FULL" | "PART" = 'FULL'

        'FULL' (default) for a complete cut, 'PART' to leave a small uncut section.

      • feed: boolean = true

        Feed paper before cutting (default: true).

      Returns void

      Error if mode is not 'FULL' or 'PART'.

      1.0.0

    • Send a hardware control command to the printer.

      Action Command Effect
      'INIT' ESC @ Clear print buffer and reset modes to defaults
      'SELECT' ESC = Select printer as the active peripheral
      'RESET' ESC ? Soft reset

      Parameters

      • action: "INIT" | "SELECT" | "RESET"

        One of 'INIT', 'SELECT', or 'RESET'.

      Returns void

      Error if action is not one of the three valid values.

      1.0.0

    • Print an image from a file path or raw image Buffer.

      Supported formats: PNG, JPEG, BMP, GIF, TIFF.

      The image is:

      1. Loaded and decoded (alpha channel composited onto white background).
      2. Converted to greyscale and thresholded at luminance 128.
      3. Optionally centred within the profile's media width.
      4. Split into vertical fragments if taller than fragmentHeight.
      5. Encoded using the selected impl and written via _raw().

      impl options:

      • 'bitImageRaster' (default) — GS v 0; widest printer compatibility.
      • 'graphics'GS ( L; better alignment on some models.
      • 'bitImageColumn'ESC *; required for printers like IT80-002.

      Parameters

      • source: string | Buffer<ArrayBufferLike>

        Absolute file path or raw image Buffer.

      • opts: ImageOptions = {}

        Image rendering options; see ImageOptions.

      Returns Promise<void>

      ImageWidthError if the image is wider than the profile's declared media width.

      await printer.image('./receipt-logo.png', { center: true });
      await printer.image('./receipt-logo.png', { impl: 'bitImageColumn' });

      1.0.0

    • Set or reset the line spacing.

      When called without arguments, resets line spacing to the printer default (ESC 2). When spacing is provided, sets the line spacing to spacing / divisor inches per dot using the matching ESC/POS command:

      Divisor Command Range
      60 ESC A 0–85
      180 ESC 3 0–255
      360 ESC + 0–255

      Parameters

      • Optionalspacing: number

        Spacing value in dots (omit to reset).

      • divisor: 60 | 180 | 360 = 180

        Unit divisor: 60, 180, or 360 (default: 180).

      Returns void

      RangeError if divisor is not one of 60 | 180 | 360.

      RangeError if spacing is outside the valid range for the divisor.

      1.0.0

    • Open the USB device, claim the interface, and locate endpoints.

      Resolves when the device is ready to receive data. Rejects with USBNotFoundError if:

      • No device matching the VID/PID is connected.
      • No bulk-OUT endpoint exists on the specified interface.

      Returns Promise<void>

      Promise that resolves when the device is open and claimed

      if the device or a suitable endpoint is not found

      1.0.0

    • Print a QR code.

      Two rendering modes are available, controlled by opts.native:

      • Software mode (native: false, default) — generates the QR matrix locally using the qrcode package and sends it as a raster image via image. Works on all printers that support raster images.

      • Native mode (native: true) — sends the five GS ( k sub-commands (set model, size, error correction, store data, print) directly. Requires the printer to have a built-in QR engine (most Epson TM series).

      Parameters

      • content: string

        The string to encode (UTF-8).

      • opts: QrOptions = {}

        QR code appearance options; see QrOptions.

      Returns Promise<void>

      Error if ec, size, or model values are outside valid ranges.

      await printer.qr('https://example.com', { size: 4, ec: QR_ECLEVEL_M });
      

      1.0.0

    • Read data from the USB bulk-IN endpoint (if present).

      Used to retrieve printer status bytes (e.g. paper-out, cover-open). If no IN endpoint was found during open, rejects immediately.

      Parameters

      • length: number = 64

        Number of bytes to request (default: 64)

      Returns Promise<Buffer<ArrayBufferLike>>

      Promise resolving with a Buffer containing received data

      if the device is not open or has no IN endpoint

      1.0.0

    • Apply text styles with full defaults merged in.

      Merges opts over a complete default set (left align, Font A, no bold, no underline, 1×1 size, density 9) before calling set. Also auto-enables customSize when width or height > 1 is requested without an explicit size mode, so callers do not need to set the flag manually.

      Calling with no arguments resets the printer to standard text defaults.

      Parameters

      • opts: TextStyleOptions = {}

        Partial style overrides (default: {} — full reset).

      Returns void

      printer.setWithDefault({ bold: true, align: 'center', height: 2 });
      printer.textln('TOTAL');
      printer.setWithDefault(); // reset all styles

      1.0.0

    • Print a row of text in software-defined columns.

      Lays out textList into adjacent fixed-width columns, word-wrapping each cell and aligning content per the corresponding align entry. Outputs one textln() call per row of the resulting grid.

      Parameters

      • textList: string[]

        Array of strings, one per column.

      • widths: number | number[]

        Total line width (split evenly) or per-column width array.

      • align: Alignment | Alignment[]

        Alignment for all columns or per-column alignment array.

      Returns void

      // Receipt item line: name left-aligned, price right-aligned
      printer.softwareColumns(['Americano', '$3.50'], [30, 10], ['left', 'right']);

      1.0.0

    • Print a string using automatic encoding selection.

      Characters are encoded via MagicEncode, which automatically selects the best code page for each segment of the string and emits the necessary ESC t n code-page-switch commands.

      Parameters

      • txt: string

        UTF-8 string to print.

      Returns void

      1.0.0

    • Validate a barcode code string against the format rules for a given barcode type.

      Checks that the code length falls within an allowed range and that the string matches the required character set for the barcode type.

      Parameters

      • bc: string

        Barcode type name (e.g. 'CODE128', 'EAN13').

      • code: string

        Barcode data string to validate.

      Returns boolean

      true if the code is valid for the given type.

      1.0.0

    • Scan for connected USB printers.

      Strategy: exclude devices whose class is definitively NOT a printer (HID, hub, audio, video, mass storage, etc.). For everything else, try to confirm via interface class 7. If the OS has claimed the device (common on Windows with usbprint.sys) and we cannot inspect interface descriptors, we include the device anyway — a claimed device on Windows is almost always a printer or printer-adjacent peripheral.

      After class detection, attempts to read the manufacturer and product name string descriptors by briefly opening the device. This fails gracefully when the device is driver-owned.

      Returns Promise<UsbDeviceInfo[]>

      Promise resolving to an array of printer UsbDeviceInfo objects

      1.0.0