mirror of
https://github.com/siemens-mobile-hacks/node-serialport-bindings-cpp.git
synced 2026-11-26 02:47:17 +00:00
44 lines
1 KiB
JavaScript
44 lines
1 KiB
JavaScript
'use strict';
|
|
const inherits = require('util').inherits;
|
|
const Transform = require('stream').Transform;
|
|
|
|
function ByteLengthParser(options) {
|
|
if (!(this instanceof ByteLengthParser)) {
|
|
return new ByteLengthParser(options);
|
|
}
|
|
Transform.call(this, options);
|
|
|
|
options = options || {};
|
|
|
|
if (typeof options.length !== 'number') {
|
|
throw new TypeError('"length" is not a number');
|
|
}
|
|
|
|
if (options.length < 1) {
|
|
throw new TypeError('"length" is not greater than 0');
|
|
}
|
|
|
|
this.length = options.length;
|
|
this.buffer = new Buffer(0);
|
|
}
|
|
|
|
inherits(ByteLengthParser, Transform);
|
|
|
|
ByteLengthParser.prototype._transform = function(chunk, encoding, cb) {
|
|
let data = Buffer.concat([this.buffer, chunk]);
|
|
while (data.length >= this.length) {
|
|
const out = data.slice(0, this.length);
|
|
this.push(out);
|
|
data = data.slice(this.length);
|
|
}
|
|
this.buffer = data;
|
|
cb();
|
|
};
|
|
|
|
ByteLengthParser.prototype._flush = function(cb) {
|
|
this.push(this.buffer);
|
|
this.buffer = new Buffer(0);
|
|
cb();
|
|
};
|
|
|
|
module.exports = ByteLengthParser;
|