nifty-wallet/app/scripts/lib/port-stream.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-12-18 22:05:16 -08:00
const Duplex = require('readable-stream').Duplex
const inherits = require('util').inherits
module.exports = PortDuplexStream
inherits(PortDuplexStream, Duplex)
2016-06-21 13:18:32 -07:00
function PortDuplexStream (port) {
2015-12-18 22:05:16 -08:00
Duplex.call(this, {
objectMode: true,
})
this._port = port
port.onMessage.addListener(this._onMessage.bind(this))
2016-01-17 01:27:25 -08:00
port.onDisconnect.addListener(this._onDisconnect.bind(this))
2015-12-18 22:05:16 -08:00
}
// private
2016-06-21 13:18:32 -07:00
PortDuplexStream.prototype._onMessage = function (msg) {
2016-03-09 18:33:30 -08:00
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)
}
2015-12-18 22:05:16 -08:00
}
2016-06-21 13:18:32 -07:00
PortDuplexStream.prototype._onDisconnect = function () {
2016-01-17 01:27:25 -08:00
try {
this.push(null)
2016-06-21 13:18:32 -07:00
} catch (err) {
2016-01-17 01:27:25 -08:00
this.emit('error', err)
}
}
2015-12-18 22:05:16 -08:00
// stream plumbing
PortDuplexStream.prototype._read = noop
2016-06-21 13:18:32 -07:00
PortDuplexStream.prototype._write = function (msg, encoding, cb) {
2016-02-10 11:46:13 -08:00
try {
2016-03-09 18:33:30 -08:00
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)
}
2016-06-21 13:18:32 -07:00
} catch (err) {
// console.error(err)
return cb(new Error('PortDuplexStream - disconnected'))
2016-02-10 11:46:13 -08:00
}
cb()
2015-12-18 22:05:16 -08:00
}
// util
2016-06-21 13:18:32 -07:00
function noop () {}