Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

var stream = require('stream');
var util = require('util');
var UInt32Native = require('./native').UInt32Native;

function Input() {
stream.Transform.call(this);
Expand Down Expand Up @@ -38,7 +39,7 @@ Input.prototype._transform = function(chunk, encoding, done) {
// Nope. Do we have enough bytes for the length?
if (self.buf.length >= 4) {
// Yep. Parse the bytes.
self.len = self.buf.readUInt32LE(0);
self.len = UInt32Native.read(self.buf, 0);
// Remove the length bytes from the buffer.
self.buf = self.buf.slice(4);
}
Expand Down Expand Up @@ -86,7 +87,7 @@ Output.prototype._transform = function(chunk, encoding, done) {
? Buffer.from(JSON.stringify(chunk))
: new Buffer(JSON.stringify(chunk));

len.writeUInt32LE(buf.length, 0);
UInt32Native.write(len, buf.length, 0);

this.push(Buffer.concat([len, buf]));

Expand Down
15 changes: 15 additions & 0 deletions native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
var os = require('os');

// Use the native byte-order of the system; can't assume little or big-endianness.
// ref https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host-protocol
var isBE = os.endianness() === 'BE';
var UInt32Native = {
read: function(buf, offset) {
return isBE ? buf.readUInt32BE(offset) : buf.readUInt32LE(offset);
},
write: function(buf, value, offset) {
return isBE ? buf.writeUInt32BE(value, offset) : buf.writeUInt32LE(value, offset);
}
};

exports.UInt32Native = UInt32Native;
5 changes: 3 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
var test = require('tape');

var nativeMessaging = require('./index');
var UInt32Native = require('./native').UInt32Native;

test('Input', function(t) {
var buf =typeof Buffer.alloc === 'function' ? Buffer.alloc(17) : new Buffer(17);
buf.writeUInt32LE(13, 0);
UInt32Native.write(buf, 13, 0);
buf.write('{"foo":"bar"}', 4);

var input = new nativeMessaging.Input();
Expand All @@ -25,7 +26,7 @@ test('Output', function(t) {

output.once('readable', function() {
var buf = output.read();
t.equal(buf.readUInt32LE(0), 13);
t.equal(UInt32Native.read(buf, 0), 13);
t.equal(buf.slice(4).toString(), '{"foo":"bar"}');
t.end();
});
Expand Down