Skip to content

Commit 4352f69

Browse files
authored
Merge pull request #7 from thorikawa/fix-port-on-is-not-a-function
Fix "this.port.on is not a function" error while connecting to the device.
2 parents f2d67e3 + 7e9c82b commit 4352f69

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

example/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ device
2323
console.log('received message:', buffer.toString());
2424
});
2525

26-
connection.write(new Buffer('Hello!', 'utf-8'));
26+
connection.write(new Buffer('Hello!', 'utf-8'), () => {
27+
console.log('wrote');
28+
});
2729
});
2830

2931
});

index.js

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,18 @@ function Connection(port, address){
1818
const self = this;
1919
this.port = port;
2020
this.address = address;
21-
this.port.on('data', function(buffer){
22-
if(buffer.length > 0){
23-
self.port.read(function(err, data){
24-
if(err) return self.emit('error', err);
25-
self.emit('data', data);
26-
});
27-
}
28-
});
21+
const read = function () {
22+
process.nextTick(function() {
23+
if (self.isOpen()) {
24+
self.port.read(function(err, data){
25+
if(err) return self.emit('error', err);
26+
self.emit('data', data);
27+
read();
28+
});
29+
}
30+
});
31+
}
32+
read();
2933
};
3034
/**
3135
* [write description]
@@ -44,9 +48,14 @@ Connection.prototype.write = function(data, callback){
4448
*/
4549
Connection.prototype.close = function(callback){
4650
this.port.close(callback);
51+
this.port = undefined;
4752
return this;
4853
};
4954

55+
Connection.prototype.isOpen = function(callback){
56+
return this.port !== undefined;
57+
};
58+
5059
/**
5160
* [inherits description]
5261
* @param {[type]} target [description]

0 commit comments

Comments
 (0)