You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.4 KiB
63 lines
1.4 KiB
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))
|
|
port.onDisconnect.addListener(this._onDisconnect.bind(this))
|
|
}
|
|
|
|
// private
|
|
|
|
PortDuplexStream.prototype._onMessage = function (msg) {
|
|
if (Buffer.isBuffer(msg)) {
|
|
delete msg._isBuffer
|
|
var data = new Buffer(msg)
|
|
// console.log('PortDuplexStream - saw message as buffer', data)
|
|
this.push(data)
|
|
} else {
|
|
// console.log('PortDuplexStream - saw message', msg)
|
|
this.push(msg)
|
|
}
|
|
}
|
|
|
|
PortDuplexStream.prototype._onDisconnect = function () {
|
|
try {
|
|
this.push(null)
|
|
} catch (err) {
|
|
this.emit('error', err)
|
|
}
|
|
}
|
|
|
|
// stream plumbing
|
|
|
|
PortDuplexStream.prototype._read = noop
|
|
|
|
PortDuplexStream.prototype._write = function (msg, encoding, cb) {
|
|
try {
|
|
if (Buffer.isBuffer(msg)) {
|
|
var data = msg.toJSON()
|
|
data._isBuffer = true
|
|
// console.log('PortDuplexStream - sent message as buffer', data)
|
|
this._port.postMessage(data)
|
|
} else {
|
|
// console.log('PortDuplexStream - sent message', msg)
|
|
this._port.postMessage(msg)
|
|
}
|
|
} catch (err) {
|
|
// console.error(err)
|
|
return cb(new Error('PortDuplexStream - disconnected'))
|
|
}
|
|
cb()
|
|
}
|
|
|
|
// util
|
|
|
|
function noop () {}
|
|
|