58 lines
1.5 KiB
JavaScript
58 lines
1.5 KiB
JavaScript
import net from 'net';
|
|
import { Adapter } from '@node-escpos/adapter';
|
|
|
|
class Network extends Adapter {
|
|
constructor(address, port = 9100, timeout = 3e4) {
|
|
super();
|
|
this.address = address;
|
|
this.port = port;
|
|
this.timeout = timeout;
|
|
this.device = new net.Socket();
|
|
}
|
|
open(callback) {
|
|
const connection_timeout = setTimeout(() => {
|
|
this.device.destroy();
|
|
callback && callback(
|
|
new Error(`printer connection timeout after ${this.timeout}ms`),
|
|
this.device
|
|
);
|
|
}, this.timeout);
|
|
this.device.on("error", (err) => {
|
|
callback && callback(err, this.device);
|
|
}).on("data", (buf) => {
|
|
console.log("printer say:", buf);
|
|
}).connect(this.port, this.address, (err) => {
|
|
clearInterval(connection_timeout);
|
|
this.emit("connect", this.device);
|
|
callback && callback(err ?? null, this.device);
|
|
});
|
|
return this;
|
|
}
|
|
write(data, callback) {
|
|
const handler = (error) => {
|
|
if (callback)
|
|
callback(error ?? null);
|
|
};
|
|
if (typeof data === "string")
|
|
this.device.write(data, handler);
|
|
else
|
|
this.device.write(data, handler);
|
|
return this;
|
|
}
|
|
read(callback) {
|
|
this.device.on("data", (buf) => {
|
|
if (callback)
|
|
callback(buf);
|
|
});
|
|
return this;
|
|
}
|
|
close(callback) {
|
|
this.device.destroy();
|
|
this.emit("disconnect", this.device);
|
|
callback && callback(null, this.device);
|
|
return this;
|
|
}
|
|
}
|
|
|
|
export { Network as default };
|