### Complete Image Printing Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/image.md A full example demonstrating how to initialize the printer, load an image, print text and the image with different raster modes, and close the printer. Includes basic error handling for device opening and printing operations. ```javascript const escpos = require('escpos'); async function printWithImage() { const device = new escpos.USB(); const printer = new escpos.Printer(device); device.open(async (err) => { if (err) { console.error('Failed to open device:', err); return; } try { // Load and print image const image = await escpos.Image.load('./logo.png'); printer .align('ct') .text('My Receipt'); // Print with double size await printer.image(image, 'd24'); // Or use raster format printer.raster(image, 'dwdh'); // Finish printer.text('Thank you!'); await printer.cut(); await printer.close(); } catch (err) { console.error('Printing error:', err); await printer.close(); } }); } printWithImage(); ``` -------------------------------- ### Method Chaining Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/README.md Demonstrates fluent syntax for chaining printer commands. Use this for sequential text formatting and operations. ```javascript printer .align('ct') .text('Title') .align('lt') .text('Content') .cut(); ``` -------------------------------- ### Status Monitoring Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/README.md Demonstrates how to retrieve and check the printer's status. This example specifically checks if the printer is offline. ```javascript const status = await printer.getStatus(escpos.PrinterStatus); if (status.toJSON().statuses[3].value === 1) { console.warn('Printer offline'); } ``` -------------------------------- ### Basic ESCPOS Printer Usage Example Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/printer/README.md Demonstrates basic printer operations including text formatting, barcode generation, table printing, and QR code generation. Ensure the appropriate adapter (USB, Network, or Serial) is installed and selected. ```javascript const escpos = require('escpos'); // install escpos-usb adapter module manually escpos.USB = require('escpos-usb'); // Select the adapter based on your printer type const device = new escpos.USB(); // const device = new escpos.Network('localhost'); // const device = new escpos.Serial('/dev/usb/lp0'); const options = { encoding: "GB18030" /* default */ } // encoding is optional const printer = new escpos.Printer(device, options); device.open(function(error){ printer .font('a') .align('ct') .style('bu') .size(1, 1) .text('The quick brown fox jumps over the lazy dog') .text('敏捷的棕色狐狸跳过懒狗') .barcode('1234567', 'EAN8') .table(["One", "Two", "Three"]) .tableCustom( [ { text:"Left", align:"LEFT", width:0.33, style: 'B' }, { text:"Center", align:"CENTER", width:0.33}, { text:"Right", align:"RIGHT", width:0.33 } ], { encoding: 'cp857', size: [1, 1] } // Optional ) .qrimage('https://github.com/song940/node-escpos', function(err){ this.cut(); this.close(); }); }); ``` -------------------------------- ### Install escpos and USB Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Install the main escpos package and the escpos-usb adapter using npm. Alternatively, install escpos-network or escpos-serialport for other connection types. ```bash npm install escpos escpos-usb # Or for network: npm install escpos escpos-network # Or for serial: npm install escpos escpos-serialport ``` -------------------------------- ### Basic Print Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/README.md Demonstrates basic text printing and cutting using a USB printer. Ensure the printer is connected via USB. ```javascript const device = new escpos.USB(); const printer = new escpos.Printer(device); device.open(() => { printer.text('Hello World').cut().close(); }); ``` -------------------------------- ### Basic USB Printer Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Connect to a USB printer and print a simple receipt. Ensure the device is opened successfully before proceeding. ```javascript const escpos = require('escpos'); escps.USB = require('escpos-usb'); const device = new escpos.USB(); const printer = new escpos.Printer(device); device.open((err) => { if (err) throw err; printer .align('ct') .text('Receipt') .text('Item: Widget') .text('Price: $9.99') .cut() .close(); }); ``` -------------------------------- ### Network Adapter Usage Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Demonstrates how to connect to a printer over a network, send text, and cut the paper. Ensure the IP address is correct and the device is accessible. ```javascript const escpos = require('escpos'); // Create adapter const device = new escpos.Network('192.168.1.100'); // Create printer const printer = new escpos.Printer(device); // Open connection device.open((err) => { if (err) { console.error('Failed:', err); return; } // Use printer printer .align('ct') .text('Hello World') .cut(); // Send data and close printer.flush().then(() => { device.close((err) => { if (err) console.error('Close error:', err); }); }); }); ``` -------------------------------- ### Testing Setup with Console and USB Adapters Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md This snippet demonstrates how to set up testing for node-escpos. It shows how to initially use the Console adapter for testing without a physical printer and then how to switch to a USB adapter for actual printing. ```javascript // Test with console first let device = new escpos.Console(); // Switch to real device when ready device = new escpos.USB(); ``` -------------------------------- ### Check Printer Status Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/statuses.md Demonstrates how to connect to a USB printer, retrieve its status, and log the interpreted status bits. It also includes a warning for offline printers. ```javascript const escpos = require('escpos'); async function checkStatus() { const device = new escpos.USB(); const printer = new escpos.Printer(device); device.open(async (err) => { const status = await printer.getStatus(escpos.PrinterStatus); const json = status.toJSON(); console.log('Printer Status:'); json.statuses.forEach(s => { console.log(`Bit ${s.bit}: ${s.label} (${s.status})`); }); if (json.statuses[3].value === 1) { console.warn('Printer is offline!'); } }); } ``` -------------------------------- ### Basic Serial Printer Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Connect to a serial printer using the specified port and baud rate. The device must be opened successfully before printing. ```javascript const escpos = require('escpos'); escps.Serial = require('escpos-serialport'); const device = new escpos.Serial('/dev/ttyUSB0', { baudRate: 9600 }); const printer = new escpos.Printer(device); device.open((err) => { if (err) throw err; printer .text('Hello Serial Printer') .cut() .close(); }); ``` -------------------------------- ### Complete Receipt System Implementation Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md This example shows a complete receipt system using node-escpos. It includes a `ReceiptPrinter` class with methods to print headers, items, and totals, handling device opening, closing, and asynchronous operations. ```javascript const escpos = require('escpos'); escpos.USB = require('escpos-usb'); class ReceiptPrinter { constructor() { this.device = new escpos.USB(); this.printer = new escpos.Printer(this.device); } async printReceipt(receipt) { return new Promise((resolve, reject) => { this.device.open(async (err) => { if (err) return reject(err); try { this._printHeader(receipt); this._printItems(receipt.items); this._printTotal(receipt); await this.printer.cut(); await this.printer.flush(); this.device.close((err) => { if (err) reject(err); else resolve(); }); } catch (err) { reject(err); } }); }); } _printHeader(receipt) { this.printer .align('ct') .size(2, 2) .text(receipt.storeName) .size(1, 1) .text(receipt.storeAddress) .newLine(); } _printItems(items) { this.printer.drawLine(); items.forEach(item => { this.printer.tableCustom([ { text: item.name, align: 'left', width: 0.6 }, { text: `$${item.price}`, align: 'right', width: 0.4 } ]); }); this.printer.drawLine(); } _printTotal(receipt) { this.printer .align('rt') .text(`Total: $${receipt.total}`) .newLine() .align('ct') .text('Thank you!'); } } // Usage const printer = new ReceiptPrinter(); printer.printReceipt({ storeName: 'MY SHOP', storeAddress: '123 Main St', items: [ { name: 'Item 1', price: '10.00' }, { name: 'Item 2', price: '5.00' } ], total: '15.00' }); ``` -------------------------------- ### Async Operations Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/README.md Shows how to handle long-running operations like image loading and flushing using Promises. Ensure images are loaded and flushed asynchronously. ```javascript const image = await escpos.Image.load('./logo.png'); const status = await printer.getStatus(PrinterStatus); await printer.image(image, 'd24'); await printer.flush(); ``` -------------------------------- ### Initialize USB Device Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/usb/README.md Instantiates a new USB device object using the Vendor ID (vid) and Product ID (pid). Ensure you have the correct drivers installed for your operating system. ```javascript const escpos = require('escpos'); escps.USB = require('escpos-usb'); const usbDevice = new escpos.USB(0x01, 0xff); ``` -------------------------------- ### Install ESCPOS via yarn Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/printer/README.md Install the ESCPOS package using yarn. This provides an alternative package management option. ```bash $ yarn add escpos ``` -------------------------------- ### Install ESCPOS via npm Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/printer/README.md Install the ESCPOS package using npm. This is the primary method for adding the dependency to your Node.js project. ```bash $ npm i escpos --save ``` -------------------------------- ### Example Custom Table Items Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/types.md Demonstrates how to create an array of CustomTableItem objects for use with Printer.tableCustom(). Shows different alignment, styling, and width/column specifications. ```typescript const items: CustomTableItem[] = [ { text: 'Item', align: 'left', width: 0.5 }, { text: 'Price', align: 'right', width: 0.5, style: 'b' }, { text: 'Qty', align: 'center', cols: 20 } ]; ``` -------------------------------- ### Monitor Printer Statuses Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/statuses.md This example demonstrates how to open a USB device, retrieve printer, paper, offline, and error statuses, and then interpret these statuses to log warnings or errors. It proceeds with printing only if the printer is online and has no errors. ```javascript const escpos = require('escpos'); async function monitorPrinter() { const device = new escpos.USB(); const printer = new escpos.Printer(device); device.open(async (err) => { if (err) { console.error('Device open error:', err); return; } try { // Get all statuses const [printerStatus, paperStatus, offlineStatus, errorStatus] = await printer.getStatuses(); // Check printer status const ps = printerStatus.toJSON(); const offline = ps.statuses.find(s => s.bit === 3); if (offline.value === 1) { console.warn('⚠ PRINTER IS OFFLINE'); } // Check paper status const pps = paperStatus.toJSON(); const paperEnd = pps.statuses.find(s => s.bit === '5,6'); if (paperEnd.value === '11') { console.error('🔴 OUT OF PAPER'); } const paperNear = pps.statuses.find(s => s.bit === '2,3'); if (paperNear.value === '11') { console.warn('🟡 PAPER NEAR END'); } // Check errors const es = errorStatus.toJSON(); const hasError = es.statuses.some( s => s.status === 'error' && s.value === 1 ); if (hasError) { console.error('❌ ERROR DETECTED'); console.log(es); } // Proceed with printing if healthy if (!offline.value && !hasError) { await printer.text('Test Print').cut().close(); } else { await printer.close(); } } catch (err) { console.error('Status check error:', err); await printer.close(); } }); } monitorPrinter(); ``` -------------------------------- ### Asynchronous Printer Operations Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Shows how to use 'await' for asynchronous printer methods such as image loading, getting status, flushing, and closing. ```javascript await printer.image(image, 'd24'); const status = await printer.getStatus(PrinterStatus); await printer.flush(); await printer.close(); ``` -------------------------------- ### Basic Network Printer Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Connect to a network printer using its IP address and print a simple text message. The device must be opened successfully. ```javascript const escpos = require('escpos'); const device = new escpos.Network('192.168.1.100'); const printer = new escpos.Printer(device); device.open((err) => { if (err) throw err; printer .text('Hello Network Printer') .cut() .close(); }); ``` -------------------------------- ### Formatted Receipt Example Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Print a detailed receipt with aligned text, lines, tables, and custom sizes. This snippet demonstrates advanced formatting options. ```javascript printer .align('ct') .size(2, 2) .text('MY SHOP') .size(1, 1) .align('lt') .newLine() .drawLine() .table(['Item', 'Price', 'Qty']) .drawLine() .table(['Widget', '$10.00', '2']) .table(['Gadget', '$5.00', '1']) .drawLine() .align('rt') .text('Total: $25.00') .newLine() .align('ct') .text('Thank you!') .cut() .close(); ``` -------------------------------- ### Set Printer Model to Star Micronics QSRiv Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md Use this to set the printer model to Star Micronics QSRiv. Includes examples of Star-specific emphasize/cancelEmphasize methods. ```javascript printer.model('qsprinter'); printer.emphasize(); // Star-specific printer.cancelEmphasize(); // Star-specific ``` -------------------------------- ### Safe Printing with Error Handling Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md This example shows how to safely print content to a USB printer, including checking for device connection errors, printer offline status, and handling potential exceptions during the printing process. It ensures the device is closed in the `finally` block. ```javascript async function safePrint() { const device = new escpos.USB(); const printer = new escpos.Printer(device); try { device.open((err) => { if (err) throw new Error('Device open failed: ' + err); }); // Check printer status before printing const status = await printer.getStatus(escpos.PrinterStatus); const json = status.toJSON(); const offline = json.statuses[3]; if (offline.value === 1) { throw new Error('Printer is offline'); } // Safe to print printer.text('Content').cut(); await printer.flush(); } catch (err) { console.error('Print failed:', err.message); } finally { device.close((err) => { if (err) console.error('Close error:', err); }); } } safePrint(); ``` -------------------------------- ### Formatted Receipt Generation Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/00-START-HERE.md Create a formatted receipt with aligned text and tables. This example demonstrates centering text, creating table headers, and drawing a line. ```javascript printer .align('ct') .text('RECEIPT') .align('lt') .table(['Item', 'Price', 'Qty']) .drawLine() .cut(); ``` -------------------------------- ### TypeScript Type Notation Examples Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/INDEX.md Illustrates various type notations used in TypeScript, including function signatures, generic classes, union types, and optional fields. Useful for understanding type definitions within the project. ```typescript // Function signature with parameters method(param: Type, optional?: Type): ReturnType // Generic classes Printer // Union types null | 'value' | string // Optional fields { field?: Type } ``` -------------------------------- ### Initialize Printer with USB Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/printer.md Demonstrates how to initialize a Printer instance using a USB adapter and set encoding and width options. The printer is then used to print 'Hello World' and cut the receipt. ```javascript const escpos = require('escpos'); const device = new escpos.USB(); const printer = new escpos.Printer(device, { encoding: 'GB18030', width: 48 }); device.open((err) => { printer.text('Hello World').cut().close(); }); ``` -------------------------------- ### Screen Constructors with Different Devices Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/screen/README.md Demonstrates how to create Screen instances using various device types like USB, Serial, Bluetooth, and Network. Ensure the respective device drivers and configurations are set up correctly before instantiation. ```javascript const usbDevice = new escpos.USB(); const usbScreen = new escpos.Screen(usbDevice); ``` ```javascript const serialDevice = new escpos.Serial('/dev/ttyUSB0'); const serialScreen = new escpos.Screen(serialDevice); ``` ```javascript const bluetoothDevice = new escpos.Bluetooth('01:23:45:67:89:AB', 1); const bluetoothScreen = new escpos.Screen(bluetoothDevice); ``` ```javascript const networkDevice = new escpos.Network('localhost'); const networkScreen = new escpos.Screen(networkDevice); ``` -------------------------------- ### Basic Printing with USB Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/api-index.md Demonstrates how to initialize a USB device and printer, print text, and cut the receipt. Ensure the device is opened before printing. ```javascript // Import const escpos = require('escpos'); escpos.USB = require('escpos-usb'); // Create device & printer const device = new escpos.USB(); const printer = new escpos.Printer(device); // Print device.open(() => { printer.text('Hello').cut().close(); }); ``` -------------------------------- ### Instantiate Serial Port Devices Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/serialport/README.md Demonstrates how to create new SerialPort instances for both Windows and Linux systems. For Linux, specific baud rate and stop bit options are shown. ```javascript const escpos = require('escpos'); escps.SerialPort = require('escpos-serialport'); const serialDeviceOnWindows = new escpos.SerialPort('COM10'); const serialDeviceOnLinux = new escpos.SerialPort('/dev/usb/lp0', { baudRate: 14400, stopBit: 2 }); ``` -------------------------------- ### USB Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/api-index.md Adapter for connecting to USB printers. Requires libusb and supports finding printers and getting specific device information. ```APIDOC ## USB Adapter ### Description USB printer adapter (requires libusb). ### Export `require('escpos-usb')` or `require('escpos').USB` ### Constructor `USB(vid?: number | Device, pid?: number)` ### Static Methods `findPrinter()` `getDevice(vid, pid): Promise` ### File `packages/usb/src/index.ts` ``` -------------------------------- ### Get All Printer Statuses Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/statuses.md Retrieves an array containing all available device statuses. This is useful for a comprehensive overview of the printer's condition. ```typescript getStatuses(): Promise ``` ```javascript const [printer, paper, offline, error] = await printer.getStatuses(); console.log('Printer:', printer.toJSON()); console.log('Paper:', paper.toJSON()); console.log('Offline cause:', offline.toJSON()); console.log('Error cause:', error.toJSON()); ``` -------------------------------- ### Initialize and Use Screen Device Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/screen.md Initializes a USB device and a Screen instance, then writes text to the display. Ensure the device is opened successfully before proceeding. The display content is automatically flushed after a delay. ```javascript const escpos = require('escpos'); const device = new escpos.USB(); const screen = new escpos.Screen(device, { encoding: 'UTF8' }); device.open((err) => { if (err) { console.error('Failed to open device:', err); return; } screen .clear() .moveHome() .text('Welcome') .move(0, 1) .text('Customer Display') .brightness(100) .cursor(false) .reverse(false) .flush(); setTimeout(() => { screen.close((err) => { if (err) console.error('Error:', err); }); }, 5000); }); ``` -------------------------------- ### Get All Printer Statuses Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/printer.md Retrieve an array containing all available printer statuses. This is useful for a comprehensive overview of the printer's current condition. ```typescript getStatuses(): Promise ``` -------------------------------- ### Instantiate Console Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Create a new Console adapter instance. You can use the default stdout handler or provide a custom function to process the output data. ```javascript const device = new escpos.Console(); // Uses default stdout const device = new escpos.Console(data => { console.log('Data:', data.toString('hex')); }); ``` -------------------------------- ### Instantiate USB Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Create a new USB adapter instance. You can auto-detect the first available printer, find a device by vendor and product IDs, or use a pre-discovered device object. ```javascript const device = new escpos.USB(); // Auto-detect const device = new escpos.USB(0x04b8, 0x0005); // Epson printer const devices = escpos.USB.findPrinter(); const device = new escpos.USB(devices[0]); ``` -------------------------------- ### Bluetooth.open() Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Establishes a connection to the Bluetooth device. An optional callback can be provided to handle connection errors. Emits a 'connect' event upon successful connection. ```APIDOC ## Bluetooth.open() ### Description Connect to Bluetooth device. An optional callback can be provided to handle connection errors. Emits a 'connect' event upon successful connection. ### Method `open(callback?: (error: Error | null) => void): this` ### Parameters #### Path Parameters - **callback** (function) - Optional - Callback function that receives an error if the connection fails. ### Emits - `'connect'` event ### Request Example ```javascript device.open((err) => { if (err) console.error('Connection failed:', err); }); ``` ``` -------------------------------- ### Printer Constructors for Different Devices Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/printer/README.md Demonstrates how to instantiate the Printer class with different device types: USB, Serial, Bluetooth, and Network. ```javascript const usbDevice = new escpos.USB(); const usbPrinter = new escpos.Printer(usbDevice); ``` ```javascript const serialDevice = new escpos.Serial('/dev/usb/lp0'); const serialPrinter = new escpos.Printer(serialDevice); ``` ```javascript const bluetoothDevice = new escpos.Bluetooth('01:23:45:67:89:AB', 1); const bluetoothPrinter = new escpos.Printer(bluetoothDevice); ``` ```javascript const networkDevice = new escpos.Network('localhost'); const networkPrinter = new escpos.Printer(networkDevice); ``` -------------------------------- ### Basic Text Printing with Node-Escpos Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/00-START-HERE.md Use this snippet to print basic text to a USB receipt printer. Ensure the escpos library is installed and a USB device is available. ```javascript const escpos = require('escpos'); const device = new escpos.USB(); const printer = new escpos.Printer(device); device.open(() => { printer.text('Hello World').cut().close(); }); ``` -------------------------------- ### Instantiate USB Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/INDEX.md Use this to create a new USB printer adapter instance. Ensure the USB device is properly connected. ```javascript new escpos.USB() ``` -------------------------------- ### Cash Drawer Kick Commands Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/commands.md Constants for kicking the cash drawer using pin 2 or pin 5. The usage example shows triggering pin 2. ```typescript export const CASH_DRAWER = { CD_KICK_2: '\x1b\x70\x00\x19\x78', // Kick pin 2 CD_KICK_5: '\x1b\x70\x01\x19\x78' // Kick pin 5 }; ``` ```javascript printer.cashdraw(2); // Trigger pin 2 (ESC p) ``` -------------------------------- ### Get Single Printer Status Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/statuses.md Retrieves a specific device status class. Use this when you need detailed information about a particular status like the printer's operational state. ```typescript getStatus( statusClass: StatusClassConstructor ): Promise ``` ```javascript const status = await printer.getStatus(escpos.PrinterStatus); const json = status.toJSON(); console.log(status.byte); // Raw byte value console.log(status.bits); // Bit array console.log(json); // Formatted response ``` -------------------------------- ### Printer Constructors Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/printer/README.md Demonstrates how to instantiate the Printer class with different device types: USB, Serial, Bluetooth, and Network. ```APIDOC ## Printer Constructors ### Printer(device) Instantiates a new Printer object, accepting a device object as an argument. **Parameters:** * **device** (object) - An instance of a device class (e.g., USB, Serial, Bluetooth, Network). ### Example Usage: ```javascript // USB Printer const usbDevice = new escpos.USB(); const usbPrinter = new escpos.Printer(usbDevice); // Serial Printer const serialDevice = new escpos.Serial('/dev/usb/lp0'); const serialPrinter = new escpos.Printer(serialDevice); // Bluetooth Printer const bluetoothDevice = new escpos.Bluetooth('01:23:45:67:89:AB', 1); const bluetoothPrinter = new escpos.Printer(bluetoothDevice); // Network Printer const networkDevice = new escpos.Network('localhost'); const networkPrinter = new escpos.Printer(networkDevice); ``` ``` -------------------------------- ### Get Specific Printer Status Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/printer.md Retrieve a specific printer status by providing a status class constructor. Use this when you need detailed information about a particular aspect of the printer's state. ```typescript getStatus( statusClass: StatusClassConstructor ): Promise ``` ```javascript const status = await printer.getStatus(escpos.PrinterStatus); console.log(status.toJSON()); ``` -------------------------------- ### Bluetooth Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Initializes a new Bluetooth adapter instance. Requires the Bluetooth device address and the RFCOMM channel number. ```APIDOC ## Bluetooth Constructor ### Description Initializes a new Bluetooth adapter instance. Requires the Bluetooth device address and the RFCOMM channel number. ### Parameters #### Path Parameters - **address** (string) - Required - Bluetooth device address (e.g., "00:11:22:33:44:55") - **channel** (number) - Required - RFCOMM channel number ### Request Example ```javascript const device = new escpos.Bluetooth('00:11:22:33:44:55', 1); ``` ``` -------------------------------- ### Screen Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/screen/README.md Initializes a new Screen instance, which can be associated with different types of devices like USB, Serial, Bluetooth, or Network. ```APIDOC ## Screen(device) ### Description Initializes a new Screen instance. ### Parameters * **device** (object) - An instance of a device (e.g., escpos.USB, escpos.Serial, escpos.Bluetooth, escpos.Network). ### Request Example ```javascript const usbDevice = new escpos.USB(); const usbScreen = new escpos.Screen(usbDevice); const serialDevice = new escpos.Serial('/dev/ttyUSB0'); const serialScreen = new escpos.Screen(serialDevice); const bluetoothDevice = new escpos.Bluetooth('01:23:45:67:89:AB', 1); const bluetoothScreen = new escpos.Screen(bluetoothDevice); const networkDevice = new escpos.Network('localhost'); const networkScreen = new escpos.Screen(networkDevice); ``` ``` -------------------------------- ### Get All Statuses Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/statuses.md Retrieves an array containing all available device statuses. This includes printer status, roll paper sensor status, offline cause status, and error cause status. ```APIDOC ## Get All Statuses ### Description Retrieves an array of all device statuses. ### Method Signature ```typescript getStatuses(): Promise ``` ### Parameters None ### Returns * **Promise** - A promise that resolves to an array of device status objects. ### Example Usage ```javascript const [printer, paper, offline, error] = await printer.getStatuses(); console.log('Printer:', printer.toJSON()); console.log('Paper:', paper.toJSON()); console.log('Offline cause:', offline.toJSON()); console.log('Error cause:', error.toJSON()); ``` ``` -------------------------------- ### Initialize Screen with Custom Encoding Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/screen.md Instantiate the Screen class with a specific device adapter and custom encoding options. This is useful when the default encoding is not suitable for your display. ```javascript const escpos = require('escpos'); const device = new escpos.USB(); const screen = new escpos.Screen(device, { encoding: 'UTF8' }); ``` -------------------------------- ### Get Single Status Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/statuses.md Retrieves a single device status based on the provided status class. The returned status object provides raw byte values, bit arrays, and a JSON representation. ```APIDOC ## Get Single Status ### Description Retrieves a single device status object. ### Method Signature ```typescript getStatus(statusClass: StatusClassConstructor): Promise ``` ### Parameters * **statusClass** (StatusClassConstructor) - Required - The constructor of the status class to retrieve. ### Returns * **Promise** - A promise that resolves to the requested device status object. ### Example Usage ```javascript const status = await printer.getStatus(escpos.PrinterStatus); const json = status.toJSON(); console.log(status.byte); console.log(status.bits); console.log(json); ``` ``` -------------------------------- ### Instantiate Serial Port Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Create a new instance of the Serial adapter for communication with a printer. Specify the serial port path and essential options like baudRate. Use the appropriate path for your operating system (e.g., /dev/ttyUSB0 for Linux/macOS, COM3 for Windows). ```javascript const device = new escpos.Serial('/dev/ttyUSB0', { baudRate: 9600 }); const device = new escpos.Serial('COM3', { baudRate: 115200 }); ``` -------------------------------- ### Instantiate Network Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/INDEX.md Use this to create a new network printer adapter instance. Provide the printer's IP address and port. ```javascript new escpos.Network(address, port) ``` -------------------------------- ### Screen Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/screen.md Initializes a new Screen instance, which controls ESC/POS display screens. It requires a device adapter and accepts optional configuration options for encoding. ```APIDOC ## Constructor Screen ### Description Initializes a new Screen instance to control ESC/POS display screens. Requires a device adapter and accepts optional configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **adapter** (`Adapter`): Required - Device adapter (Network, USB, Serial, etc.). - **options** (`ScreenOptions`): Optional - Configuration options, including `encoding` (string, default: 'GB18030'). ### Request Example ```javascript const escpos = require('escpos'); const device = new escpos.USB(); const screen = new escpos.Screen(device, { encoding: 'UTF8' }); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize Bluetooth Printer Connection Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Instantiate the Bluetooth adapter with the device address and RFCOMM channel. This prepares the adapter for connection. ```javascript const device = new escpos.Bluetooth('00:11:22:33:44:55', 1); ``` -------------------------------- ### Printer Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/printer.md Initializes a new Printer instance, managing buffered output and printer hardware communication via an adapter. ```APIDOC ## Constructor Printer ### Description Initializes a new Printer instance. It manages buffered output, text formatting, barcode generation, image rendering, and printer hardware control. The Printer works with an Adapter to communicate with actual hardware devices. ### Parameters #### Path Parameters - **adapter** (Adapter) - Required - An adapter instance (Network, USB, Serial, Bluetooth, or Console) that handles device communication - **options** (PrinterOptions) - Required - Configuration object for encoding and display width ### Request Example ```javascript const escpos = require('escpos'); const device = new escpos.USB(); const printer = new escpos.Printer(device, { encoding: 'GB18030', width: 48 }); device.open((err) => { printer.text('Hello World').cut().close(); }); ``` ``` -------------------------------- ### Get Specific USB Device by ID Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Retrieve a specific USB device using its vendor ID (vid) and product ID (pid). This method returns a Promise that resolves with the device object or rejects if the device is not found. ```javascript try { const device = await escpos.USB.getDevice(0x04b8, 0x0005); // Use device... } catch (err) { console.error('Device not found:', err); } ``` -------------------------------- ### Instantiate Bluetooth Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/INDEX.md Use this to create a new Bluetooth printer adapter instance. Provide the printer's MAC address and Bluetooth channel. ```javascript new escpos.Bluetooth(address, channel) ``` -------------------------------- ### USBAdapter Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Initializes a new USBAdapter instance. It can auto-detect the first available printer, find a printer by vendor and product IDs, or use a pre-selected device object. ```APIDOC ## USBAdapter Constructor ### Description Initializes a new USBAdapter instance. It can auto-detect the first available printer, find a printer by vendor and product IDs, or use a pre-selected device object. ### Parameters #### Path Parameters - **vid** (number, optional) - USB vendor ID - **pid** (number, optional) - USB product ID ### Behavior - No arguments: Auto-detects first available printer - `vid` only: Uses device object from `findPrinter()` - `vid` and `pid`: Finds device by IDs ### Example ```javascript const device = new escpos.USB(); // Auto-detect const device = new escpos.USB(0x04b8, 0x0005); // Epson printer const devices = escpos.USB.findPrinter(); const device = new escpos.USB(devices[0]); ``` ``` -------------------------------- ### Instantiate Console Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/INDEX.md Use this to create a new console printer adapter instance. This is useful for debugging or testing without a physical printer. ```javascript new escpos.Console() ``` -------------------------------- ### USBAdapter Instance Methods Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Methods for interacting with an opened USB device, including opening, writing data, reading responses, and closing the connection. ```APIDOC ## Methods ### open(callback?: (error: Error | null) => void): this #### Description Open USB device. #### Behavior - Opens device - Detaches kernel driver (non-Windows) - Claims interface - Finds output/input endpoints - Emits `'connect'` event #### Example ```javascript device.open((err) => { if (err) console.error('Open failed:', err); }); ``` ### write(data: string | Buffer, callback?: (error: Error | null) => void): this #### Description Write data to printer. ### read(callback?: (data: Buffer) => void): void #### Description Read response from printer. ### close(callback?: (error: Error | null) => void, timeout?: number): this #### Description Close device and release interface. ``` -------------------------------- ### Project File Structure Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/api-index.md This outlines the directory structure of the project, detailing the purpose of each main directory and its subdirectories. ```tree packages/ ├── adapter/ # Base adapter interface │ └── src/index.ts ├── printer/ # Main Printer class │ ├── src/ │ │ ├── index.ts # Printer class │ │ ├── commands.ts # ESC/POS constants │ │ ├── statuses.ts # Status classes │ │ ├── image.ts # Image class │ │ ├── utils.ts # Utilities │ │ └── tsconfig.json │ └── package.json ├── network/ # Network adapter │ ├── src/index.ts │ └── package.json ├── usb/ # USB adapter │ ├── src/index.ts │ └── package.json ├── serialport/ # Serial adapter │ ├── src/index.ts │ └── package.json ├── bluetooth/ # Bluetooth adapter │ ├── index.js │ └── package.json ├── console/ # Console debug adapter │ ├── src/index.ts │ └── package.json ├── screen/ # Screen class │ ├── src/ │ │ ├── index.ts │ │ ├── commands.ts │ │ └── tsconfig.json │ └── package.json └── server/ # (Placeholder) ``` -------------------------------- ### Instantiate Serial Adapter Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/INDEX.md Use this to create a new serial printer adapter instance. Specify the serial port and any necessary options. ```javascript new escpos.Serial(port, options) ``` -------------------------------- ### Method Chaining for Receipt Generation Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/README.md Shows how to chain multiple printer commands to format and print a receipt. This pattern allows for concise and readable code. ```javascript printer .align('ct') .size(2, 2) .text('RECEIPT') .size(1, 1) .align('lt') .table(['Item', 'Price']) .drawLine() .cut() .close(); ``` -------------------------------- ### Chaining Screen Methods Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/screen.md Demonstrates method chaining for manipulating screen content and properties. This allows for a more readable and concise way to perform multiple operations sequentially. ```javascript screen .clear() .moveHome() .text('Hello') .move(0, 1) .text('World') .brightness(100) .cursor(false) .flush(); ``` -------------------------------- ### Console Adapter Methods Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Provides methods for interacting with the Console Adapter, including opening, writing, and closing the connection. ```APIDOC ## Console Adapter Methods ### open #### Description Opens the console connection. This is a no-operation method and always succeeds. #### Method `open(callback?: (error: Error | null) => void): this` ### write #### Description Writes data to the console handler. #### Method `write(data: string | Buffer, callback?: (error: Error | null) => void): this` ### close #### Description Closes the console connection. This is a no-operation method. #### Method `close(callback?: (error: Error | null) => void): this` ### read #### Description Reading data is not supported by the Console Adapter. #### Method `read(): NotImplementedException` ``` -------------------------------- ### Serial Port Adapter Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Initializes a new Serial Port Adapter instance. You can specify the serial port path and options such as baud rate. ```APIDOC ## Serial Port Adapter Constructor ### Description Initializes a new Serial Port Adapter instance. You can specify the serial port path and options such as baud rate. ### Parameters #### Path Parameters - **port** (string) - Required - Serial port path (e.g., `/dev/ttyUSB0`, `COM3`) #### Query Parameters - **options** (object) - Required - SerialPort options (baudRate, etc.) ### Request Example ```javascript const device = new escpos.Serial('/dev/ttyUSB0', { baudRate: 9600 }); const device = new escpos.Serial('COM3', { baudRate: 115200 }); ``` ``` -------------------------------- ### Basic Printer Operations with ESC/POS Source: https://github.com/lsongdev/node-escpos/blob/v3/README.md This snippet demonstrates how to initialize a printer connection, format text, add a barcode, print tables, and generate a QR code using the node-escpos library. It covers common printer functionalities for receipt generation. ```javascript const escpos = require('escpos'); // install escpos-usb adapter module manually espos.USB = require('escpos-usb'); // Select the adapter based on your printer type const device = new escpos.USB(); // const device = new escpos.Network('localhost'); // const device = new escpos.Serial('/dev/usb/lp0'); const options = { encoding: "GB18030" /* default */ } // encoding is optional const printer = new escpos.Printer(device, options); device.open(function(error){ printer .font('a') .align('ct') .style('bu') .size(1, 1) .text('The quick brown fox jumps over the lazy dog') .text('敏捷的棕色狐狸跳过懒狗') .barcode('1234567', 'EAN8') .table(["One", "Two", "Three"]) .tableCustom( [ { text:"Left", align:"LEFT", width:0.33, style: 'B' }, { text:"Center", align:"CENTER", width:0.33}, { text:"Right", align:"RIGHT", width:0.33 } ], { encoding: 'cp857', size: [1, 1] } // Optional ) .qrimage('https://github.com/song940/node-escpos', function(err){ this.cut(); this.close(); }); }); ``` -------------------------------- ### Initialize Console Device Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/console/README.md Instantiate the Console device for debugging ESC/POS commands. This device prints commands to standard output. ```javascript const escpos = require('escpos'); escps.Console = require('escpos-console'); const debugDevice = new escpos.Console(); ``` -------------------------------- ### Network Adapter Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Initializes a new Network adapter instance to connect to a network printer. You can specify the IP address, port, and connection timeout. ```APIDOC ## Network Adapter Constructor ### Description Initializes a new Network adapter instance to connect to a network printer. You can specify the IP address, port, and connection timeout. ### Constructor ```typescript constructor(address: string, port = 9100, timeout = 30000) ``` ### Parameters #### Path Parameters - **address** (string) - Required - IP address of network printer - **port** (number) - Optional - TCP port number, defaults to `9100` - **timeout** (number) - Optional - Connection timeout in milliseconds, defaults to `30000` ### Request Example ```javascript const escpos = require('escpos'); const device = new escpos.Network('192.168.1.100'); const device = new escpos.Network('192.168.1.100', 9100, 20000); ``` ``` -------------------------------- ### Console Adapter Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Initializes the Console Adapter. It can optionally take a custom handler function to process the output data, otherwise it defaults to printing hex bytes to stdout. ```APIDOC ## Console Adapter Constructor ### Description Initializes the Console Adapter. It can optionally take a custom handler function to process the output data, otherwise it defaults to printing hex bytes to stdout. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```typescript constructor(handler?: (data: string | Buffer) => void) ``` ### Parameters - **handler** (function) - Optional - Custom handler for output data. Defaults to printing hex bytes in 8-byte groups to stdout. ### Example ```javascript // Uses default stdout handler const device = new escpos.Console(); // Uses a custom handler const device = new escpos.Console(data => { console.log('Data:', data.toString('hex')); }); ``` ``` -------------------------------- ### Initialize Bluetooth Printer Connection Source: https://github.com/lsongdev/node-escpos/blob/v3/packages/bluetooth/README.md Establishes a connection to a Bluetooth printer using its MAC address and channel. Ensure the Bluetooth adapter is enabled and the printer is discoverable. ```javascript const escpos = require('escpos'); escps.Bluetooth = require('escpos-bluetooth'); const address = '01:23:45:67:89:AB'; const channel = 1; const bluetoothDevice = new escpos.Bluetooth(address, channel); ``` -------------------------------- ### Async Image Print Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/README.md Illustrates how to load and print an image asynchronously. The image path must be correct and accessible. ```javascript async function printLogo() { const image = await escpos.Image.load('./logo.png'); await printer.image(image, 'd24'); } ``` -------------------------------- ### List Serial Ports Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/quick-start.md This snippet demonstrates how to list available serial ports and configure a connection to a specific port with a given baud rate. Ensure the serial port path is correct. ```javascript const device = new escpos.Serial('/dev/ttyUSB0', { baudRate: 9600 }); const ports = await device.list(); console.log(ports); ``` -------------------------------- ### Network Adapter Constructor Source: https://github.com/lsongdev/node-escpos/blob/v3/_autodocs/adapters.md Instantiates a Network adapter for connecting to a network printer. Specify the IP address and optionally the TCP port and connection timeout. ```javascript const escpos = require('escpos'); const device = new escpos.Network('192.168.1.100'); const device = new escpos.Network('192.168.1.100', 9100, 20000); ```