node-thermal-printer
Version:
Print on Epson, Star, Tranca, Daruma and Brother thermal printers with Node.js
80 lines (60 loc) • 2.59 kB
JavaScript
const usb = require('usb');
const ThermalPrinter = require('../node-thermal-printer').printer;
const Types = require('../node-thermal-printer').types;
function getStringDescriptor(device, descriptorIndex) {
const stringDescriptor = device.getStringDescriptor(descriptorIndex);
return stringDescriptor ? stringDescriptor.toString() : '';
}
// Get a list of USB devices
const devices = usb.getDeviceList();
// Display information about each device
devices.forEach((device, index) => {
console.log(`Device ${index + 1}:`);
console.log(` Device Name: ${getStringDescriptor(device, device.deviceDescriptor.iProduct)}`);
console.log(` Vendor ID: ${device.deviceDescriptor.idVendor}`);
console.log(` Product ID: ${device.deviceDescriptor.idProduct}`);
console.log('--------------------------------------');
});
// List all USB devices
usb.getDeviceList().forEach((device) => {
console.log(`Device: ${device.deviceDescriptor.idVendor}:${device.deviceDescriptor.idProduct}`);
});
usb.on('attach', function (device) {
console.log(`Attach: ${device.deviceDescriptor.idVendor}:${device.deviceDescriptor.idProduct}`);
});
// Replace these values with your printer's Vendor ID and Product ID
const vendorId = 4070; // Vendor ID
const productId = 33054; // Product ID
// const vendorId = 1305; // Vendor ID
// const productId = 3; // Product ID
const device = usb.findByIds(vendorId, productId);
if (device) {
console.log(`Found your printer: ${vendorId}:${productId}`);
// Open the USB device
device.open();
// Define your control transfer parameters and command
const bmRequestType = usb.LIBUSB_REQUEST_TYPE_CLASS;
const bRequest = 0x01; // Custom control request (replace with the correct value)
const wValue = 0x0000; // Replace with the correct value
const wIndex = 0x0000; // Replace with the correct value
const dataBuffer = Buffer.alloc(4); // Buffer for data, if any
const printer = new ThermalPrinter({
type: Types.EPSON,
interface: process.argv[2],
});
printer.getStatus();
console.log(dataBuffer, printer.getBuffer())
// Send the control transfer
device.controlTransfer(bmRequestType, bRequest, wValue, wIndex, printer.getBuffer(), (error, data) => {
console.log(error, data)
if (error) {
console.error('Control transfer error:', error);
} else {
console.log('Control transfer data:', data);
}
// Close the USB device when done
device.close();
});
} else {
console.log('Printer not found');
}