从 node-serialport 版本 2 或 3 开始,解析器必须继承 Stream.Tansform 类。在您的示例中,这将成为一个新课程。
创建一个名为 CustomParser.js 的文件:
class CustomParser extends Transform {
constructor() {
super();
this.incommingData = Buffer.alloc(0);
}
_transform(chunk, encoding, cb) {
// chunk is the incoming buffer here
this.incommingData = Buffer.concat([this.incommingData, chunk]);
if (this.incommingData.length > 3 && this.incommingData[this.incommingData.length - 3] == 3) {
this.push(this.incommingData); // this replaces emitter.emit("data", incomingData);
this.incommingData = Buffer.alloc(0);
}
cb();
}
_flush(cb) {
this.push(this.incommingData);
this.incommingData = Buffer.alloc(0);
cb();
}
}
module.exports = CustomParser;
他们像这样使用您的解析器:
var SerialPort = require('serialport');
var CustomParser = require('./CustomParser ');
var port = new SerialPort('COM1');
var customParser = new CustomParser();
port.pipe(customParser);
customParser.on('data', function(data) {
console.log(data);
});