Skip to content

Commit

Permalink
Merge pull request #10 from thorikawa/delimiter
Browse files Browse the repository at this point in the history
Add delimiter property for incoming data.
  • Loading branch information
lsongdev authored Oct 27, 2017
2 parents b350e07 + ac10d91 commit 01eb723
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ device
bluetooth.connect(address, channel, function(err, connection){
if(err) return console.error(err);

connection.delimiter = Buffer.from('\n', 'utf8');
connection.on('data', (buffer) => {
console.log('received message:', buffer.toString());
});
Expand Down
15 changes: 13 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,23 @@ function Connection(port, address){
const self = this;
this.port = port;
this.address = address;
this.buffer = new Buffer(0);
const read = function () {
process.nextTick(function() {
if (self.isOpen()) {
self.port.read(function(err, data){
self.port.read(function(err, chunk){
if(err) return self.emit('error', err);
self.emit('data', data);
if (self.delimiter) {
let data = Buffer.concat([self.buffer, chunk]);
let position;
while ((position = data.indexOf(self.delimiter)) !== -1) {
self.emit('data', data.slice(0, position));
data = data.slice(position + self.delimiter.length);
}
self.buffer = data;
} else {
self.emit('data', chunk);
}
read();
});
}
Expand Down

0 comments on commit 01eb723

Please sign in to comment.