const EventEmitter = require('events') const escpos = require('escpos') const config = require('./config.json') const fs = require('fs') // const device = new escpos.Serial(config.printer.serial) // const printer = new escpos.Printer(device) // let isOpen = false class PrinterDevice { constructor() { this._isOpen = false this._device = null this._printer = null this._type = null // type = serial or console } async connect() { let chkSerial = await new Promise((resolve, reject) => { fs.access(config.printer.serial, err => { if (err) return resolve(false) return resolve(true) }) }) if (chkSerial) { this._device = new escpos.Serial(config.printer.serial) this._type = 'serial' } else { this._device = new escpos.Console() this._type = 'console' } this._printer = new escpos.Printer(this._device) this.openSerial() } async openSerial() { if (!this._device || this._type != 'serial') return this._isOpen = await new Promise((resolve, reject) => { this._device.open(err => { if (err) return resolve(false) return resolve(true) }) }) } printerString(str) { if (!this._isOpen || !this._printer) return let strs = str.split(/\n/) this._printer.font('a') .align('ct') .size(1, 1) for (let i in strs) { printer.text(strs[i], 'big5') } printer.cut(true, 8) } get isOpen() { return this._isOpen ? true : false } } module.exports = new PrinterDevice()