0

Hello i am creating an express service that prints to a pos printer at http request. The problem is that my solution does not print images on the first print but it does at the second and so on.

I am using https://github.com/song940/node-escpos

Here is my server.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')
});

Here is my print.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();
    });
};
gogibogi4
  • 263
  • 4
  • 15

2 Answers2

0

Since this hasn't been answered yet I will provide the solution that worked for me. The problem was that the images were starting to load on the first time I submitted a request. By the second time I submitted a request the images were already loaded and were successfully printed.

I solved the problem by a adding a check that would not allow to print until the images were loaded.

gogibogi4
  • 263
  • 4
  • 15
0

replace printSettings.forEach to simple for() cycle. I think problem in async image loading inside forEach

Yevhen
  • 791
  • 9
  • 24