2015-12-19 07:05:16 +01:00
|
|
|
const Duplex = require('readable-stream').Duplex
|
|
|
|
const inherits = require('util').inherits
|
2017-10-21 21:06:39 +02:00
|
|
|
const noop = function () {}
|
2015-12-19 07:05:16 +01:00
|
|
|
|
|
|
|
module.exports = PortDuplexStream
|
|
|
|
|
|
|
|
inherits(PortDuplexStream, Duplex)
|
|
|
|
|
2016-06-21 22:18:32 +02:00
|
|
|
function PortDuplexStream (port) {
|
2015-12-19 07:05:16 +01:00
|
|
|
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
|
|
|
|
|
2016-06-21 22:18:32 +02:00
|
|
|
PortDuplexStream.prototype._onMessage = function (msg) {
|
2016-03-10 03:33:30 +01:00
|
|
|
if (Buffer.isBuffer(msg)) {
|
|
|
|
delete msg._isBuffer
|
|
|
|
var data = new Buffer(msg)
|
|
|
|
this.push(data)
|
|
|
|
} else {
|
|
|
|
this.push(msg)
|
|
|
|
}
|
2015-12-19 07:05:16 +01:00
|
|
|
}
|
|
|
|
|
2016-06-21 22:18:32 +02:00
|
|
|
PortDuplexStream.prototype._onDisconnect = function () {
|
2017-09-08 06:17:49 +02:00
|
|
|
this.destroy()
|
2016-01-17 10:27:25 +01:00
|
|
|
}
|
|
|
|
|
2015-12-19 07:05:16 +01:00
|
|
|
// stream plumbing
|
|
|
|
|
|
|
|
PortDuplexStream.prototype._read = noop
|
|
|
|
|
2016-06-21 22:18:32 +02:00
|
|
|
PortDuplexStream.prototype._write = function (msg, encoding, cb) {
|
2016-02-10 20:46:13 +01:00
|
|
|
try {
|
2016-03-10 03:33:30 +01:00
|
|
|
if (Buffer.isBuffer(msg)) {
|
|
|
|
var data = msg.toJSON()
|
|
|
|
data._isBuffer = true
|
|
|
|
this._port.postMessage(data)
|
|
|
|
} else {
|
|
|
|
this._port.postMessage(msg)
|
|
|
|
}
|
2016-06-21 22:18:32 +02:00
|
|
|
} catch (err) {
|
2017-01-12 04:09:49 +01:00
|
|
|
return cb(new Error('PortDuplexStream - disconnected'))
|
2016-02-10 20:46:13 +01:00
|
|
|
}
|
2017-01-12 04:09:49 +01:00
|
|
|
cb()
|
2015-12-19 07:05:16 +01:00
|
|
|
}
|