node-escpos Printer Driver

repository·main·Indexed 18 days ago

https://github.com/node-escpos/driver

An ESC/POS printer driver for Node.js that enables communication with thermal printers via various protocols. It includes a core Printer class for managing buffers and formatting, an abstract Adapter class for custom connection methods, and built-in adapters for Bluetooth and Console debugging. The library supports text styling, alignment, barcode and QR code generation, image processing (bitmap and raster conversion), and hardware control for cash drawers and paper cutting.

Tokens
10.4K
Snippets
36
Records
48
Agent score
63%

What's inside node-escpos

  1. Initialize the Printer class

    main

    To use the library, instantiate the Printer class by providing an Adapter (e.g., USB, Network, or SerialPort) and a PrinterOptions object. The Printer class manages an internal buffer of ESC/POS commands which are sent to the hardware when flush() is called.

    PrinterOptions:

    • encoding (string, optional): The character encoding to use for text (defaults to GB18030).
    • width (number, optional): The printer width in characters (defaults to 48).
    import Printer from '@node-escpos/core/Printer';
    import USBAdapter from '@node-escpos/usb-adapter';
    
    const adapter = new USBAdapter();
    const options = { encoding: 'utf8', width: 42 };
    const printer = new Printer(adapter, options);
  2. Use the Bluetooth adapter to connect to printers

    main

    The Bluetooth class is an adapter used to communicate with ESC/POS printers via Bluetooth. It uses the @abandonware/noble library to scan for peripherals.

    To use it, instantiate the class with the target device's address. The adapter automatically handles scanning for services and characteristics (specifically looking for service 18f0 and characteristic 2af1).

    Common workflow:

    1. Instantiate Bluetooth with the device address.
    2. Call .open() to establish a connection.
    3. Use .write(data) to send commands or text to the printer.
    4. Call .close() to disconnect.
    import Bluetooth from '@node-escpos/bluetooth-adapter';
    
    const bluetooth = new Bluetooth('DEVICE_ADDRESS_HERE');
    
    bluetooth.open((err) => {
      if (err) return console.error(err);
      
      bluetooth.write('Hello World\n', (err) => {
        if (err) console.error(err);
        bluetooth.close();
      });
    });
  3. Configure ScreenOptions

    main

    When instantiating the Screen class, you can pass a ScreenOptions object to configure the character encoding used for text operations.

    KeyTypeDescription
    encodingstringThe character encoding to use (e.g., 'GB18030', 'utf-8').
    const options = { encoding: 'GB18030' };
    const screen = new Screen(adapter, options);
  4. Serial.open()

    main

    Opens the serial port connection.

    Parameters:

    • callback?: An optional function called with (error: Error | null) once the port attempt is complete.

    Returns: this (the Serial instance) to allow chaining.

    Throws: `Error(

  5. Write data to the printer with USBAdapter.write()

    main

    Send data to the printer using the .write() method. It accepts a string or Buffer and returns this to allow chaining. You can provide an optional callback to handle errors or confirm the transfer completion.

    // Writing a Buffer
    adapter.write(Buffer.from([0x1B, 0x40]), (err) => {
      if (err) console.error('Write error:', err);
    });
    
    // Writing a string
    adapter.write('Hello World\n');
  6. Initialize the Screen class

    main

    The Screen class provides an interface for controlling the display screen of an ESC/POS printer. It requires an Adapter (such as USB, Network, or SerialPort) to communicate with the hardware. You can optionally provide ScreenOptions to set the character encoding.

    By default, the encoding is set to "GB18030" if not specified.

    import Screen from '@node-escpos/screen';
    // Assuming 'adapter' is an instance of an ESC/POS adapter
    const screen = new Screen(adapter, { encoding: 'utf-8' });
  7. Retrieve a device by Serial Number or VID/PID

    main

    The USBAdapter provides static helper methods to find and open specific USB devices before passing them to an adapter:

    • USBAdapter.getDevice(vid, pid): Returns a Promise that resolves with an opened usb.Device matching the provided Vendor ID and Product ID.
    • USBAdapter.getDeviceBySerial(serialNumber): Returns a Promise that resolves with an opened usb.Device matching the provided serial number string.
    // By VID/PID
    const device = await USBAdapter.getDevice(0x04b8, 0x0202);
    const adapter = new USBAdapter(device);
    
    // By Serial Number
    const device = await USBAdapter.getDeviceBySerial('12345678');
    const adapter = new USBAdapter(device);
  8. Use timer and status features

    main

    The Screen class supports displaying a timer and managing DTR signals.

    • timer(h: number, m: number): Sets the counter time and displays it in the bottom right of the screen.
    • displayTimer(): Displays the time counter at the right side of the bottom line.
    • DTR(n: boolean): Sets status confirmation for the DTR signal.
  9. Initialize the USBAdapter

    main

    The USBAdapter class is used to connect to ESC/POS printers via USB. You can initialize it in three ways:

    1. By Vendor ID (VID) and Product ID (PID): Pass vid and pid as numbers.
    2. By an existing USB Device object: Pass a usb.Device instance (e.g., obtained from USBAdapter.findPrinter()).
    3. Automatic Discovery: If no arguments are provided, the adapter attempts to find the first available printer using USBAdapter.findPrinter().

    If no compatible printer is found during initialization, the constructor throws an error: "Can not find printer".

    import USBAdapter from '@node-escpos/usb-adapter';
    
    // Option 1: Using VID and PID
    const adapter = new USBAdapter(0x04b8, 0x0202);
    
    // Option 2: Using a specific device object
    const devices = USBAdapter.findPrinter();
    const adapter = new USBAdapter(devices[0]);
    
    // Option 3: Automatic discovery
    const adapter = new USBAdapter();
  10. Interpret printer status bytes with status classes

    main

    The @node-escpos/core package provides several classes to parse raw status bytes received from an ESC/POS printer into human-readable JSON. Each class corresponds to a specific type of status command. You can instantiate these classes by passing the raw byte received from the printer and then call .toJSON() to get a structured report of the printer's state.

    Available status classes:

    • PrinterStatus: General printer state (Online/Offline, Drawer status, etc.).
    • OfflineCauseStatus: Reasons why the printer might be offline (Cover open, Paper end, etc.).
    • ErrorCauseStatus: Specific error types (Autocutter error, Unrecoverable error, etc.).
    • RollPaperSensorStatus: Status of paper levels (Paper near-end, Paper present).

    Each .toJSON() output includes a statuses array containing the bit position, the value (0 or 1), a descriptive label, and a status level (ok, warning, or error).

    import { PrinterStatus } from '@node-escpos/core';
    
    // Assuming 'byte' is the raw number received from the printer
    const status = new PrinterStatus(byte);
    const report = status.toJSON();
    
    console.log(report.statuses);
    // Output example: [{ bit: 3, value: 0, label: 'Online', status: 'ok' }, ... ]
  11. Flush and Close the Screen instance

    main

    Because the Screen class uses an internal buffer to collect commands, you must call flush() to send the accumulated data to the hardware via the adapter.

    • flush(): Sends all buffered data to the adapter.
    • close(callback, ...args): Flushes the buffer and then closes the adapter connection. The callback receives an Error | null.
    screen.flush();
    
    screen.close((err) => {
      if (err) console.error(err);
      else console.log('Closed successfully');
    });