您好,我正在创建一个快速服务,该服务在http请求下打印到pos打印机。问题是我的解决方案不会在第一次打印时打印图像,但在第二次打印时会打印图像,依此类推。
我正在使用 https://github.com/song940/node-escpos
这是我的服务器.js
var print = require('./print')
var express = require('express')
var cors = require('cors')
var bodyParser = require('body-parser');
var app = express();
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.get('/print', cors(corsOptions), (req, res) => {
print.demoPrint();
return res.send(req.body);
});
app.listen(3000, () => {
console.log('Express server is started')
});
这是我的印刷品.js
const escpos = require('escpos');
const device = new escpos.USB(0x1504,0x003d);
const options = { encoding: "GB18030"};
const printer = new escpos.Printer(device);
const fs = require('fs')
const printSettings = JSON.parse(fs.readFileSync('printConfig.json', 'utf8'));
exports.demoPrint = () => {
device.open(function() {
printSettings.forEach((currentLine) => {
if(currentLine.printType === "text") {
console.log("PRINTING TEXT");
printer
.font(currentLine.font)
.align(currentLine.align)
.style('bu')
.size(currentLine.size, currentLine.size)
.text(currentLine.text)
}
else if(currentLine.printType === "image") {
escpos.Image.load(currentLine.path, (image) => {
console.log("PRINTING IMAGE");
printer
.align(currentLine.align)
.size(currentLine.size, currentLine.size)
.image(image)
});
}
else if(currentLine.printType === "barcode") {
console.log("PRINTING BARCODE");
printer
.align(currentLine.align)
.barcode(currentLine.text, 'CODE39', {
height: 64,
font: 'B'
});
}
});
printer
.text('n')
.text('n')
.cut()
.close();
});
};
由于这个问题还没有得到回答,我将提供对我有用的解决方案。问题是图像在我第一次提交请求时开始加载。当我第二次提交请求时,图像已经加载并成功打印。
我通过添加检查解决了这个问题,该检查在加载图像之前不允许打印。
将printSettings.forEach替换为简单的for((循环。我认为在内部异步加载图像时存在问题