2015-12-19 07:05:16 +01:00
|
|
|
const Duplex = require('readable-stream').Duplex
|
|
|
|
const inherits = require('util').inherits
|
|
|
|
|
|
|
|
module.exports = PortDuplexStream
|
|
|
|
|
|
|
|
|
|
|
|
inherits(PortDuplexStream, Duplex)
|
|
|
|
|
|
|
|
function PortDuplexStream(port){
|
|
|
|
Duplex.call(this, {
|
|
|
|
objectMode: true,
|
|
|
|
})
|
|
|
|
this._port = port
|
|
|
|
port.onMessage.addListener(this._onMessage.bind(this))
|
2016-01-17 10:27:25 +01:00
|
|
|
port.onDisconnect.addListener(this._onDisconnect.bind(this))
|
2015-12-19 07:05:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// private
|
|
|
|
|
|
|
|
PortDuplexStream.prototype._onMessage = function(msg){
|
|
|
|
// console.log('PortDuplexStream - saw message', msg)
|
|
|
|
this.push(msg)
|
|
|
|
}
|
|
|
|
|
2016-01-17 10:27:25 +01:00
|
|
|
PortDuplexStream.prototype._onDisconnect = function(msg){
|
|
|
|
// console.log('PortDuplexStream - saw message', msg)
|
|
|
|
try {
|
|
|
|
this.end()
|
|
|
|
} catch(err){
|
|
|
|
this.emit('error', err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-19 07:05:16 +01:00
|
|
|
// stream plumbing
|
|
|
|
|
|
|
|
PortDuplexStream.prototype._read = noop
|
|
|
|
|
|
|
|
PortDuplexStream.prototype._write = function(msg, encoding, cb){
|
|
|
|
// console.log('PortDuplexStream - sent message', msg)
|
2016-02-10 20:46:13 +01:00
|
|
|
try {
|
|
|
|
this._port.postMessage(msg)
|
|
|
|
cb()
|
|
|
|
} catch(err){
|
|
|
|
// this.emit('error', err)
|
|
|
|
cb(new Error('PortDuplexStream - disconnected'))
|
|
|
|
}
|
2015-12-19 07:05:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// util
|
|
|
|
|
|
|
|
function noop(){}
|