Skip to content

Commit

Permalink
Merge pull request #36 from cvlchinet/patch
Browse files Browse the repository at this point in the history
Allow sending binary data without ArrayBuffer (e. g. IE8)
  • Loading branch information
rauchg committed Dec 10, 2014
2 parents d0642f0 + 2c1becc commit e53e9f5
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
return encodeBlob(packet, supportsBinary, callback);
}

// might be an object with { base64: true, data: dataAsBase64String }
if (data && data.base64) {
return encodeBase64Object(packet, callback);
}

// Sending data as a utf-8 string
var encoded = packets[packet.type];

Expand All @@ -115,6 +120,12 @@ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {

};

function encodeBase64Object(packet, callback) {
// packet data is an object { base64: true, data: dataAsBase64String }
var message = 'b' + exports.packets[packet.type] + packet.data.data;
return callback(message);
}

/**
* Encode packet helpers for binary types
*/
Expand Down
41 changes: 41 additions & 0 deletions test/browser/base64_object.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

/**
* Test dependencies.
*/

var parser = require('../../lib/browser.js');
var expect = require('expect.js');

/**
* Shortcuts
*/
var encPayload = parser.encodePayload;
var decPayload = parser.decodePayload;

/**
* Tests.
*/
describe('parser', function() {
it('should encode/decode mixed base64 object and string', function(done) {
var data = new Buffer(5);
for (var i = 0; i < data.length; i++) data[i] = i;
var msg = { base64: true, data: new Buffer(data).toString('base64') };
encPayload([{ type: 'message', data: msg }, { type: 'message', data: 'hello' }], function(encoded) {
decPayload(encoded,
function(packet, index, total) {
var isLast = index + 1 == total;
expect(packet.type).to.eql('message');
if (!isLast) {
if (!global.ArrayBuffer) {
expect(packet.data).to.eql(msg);
} else {
expect(new Int8Array(packet.data)).to.eql(new Int8Array(data));
}
} else {
expect(packet.data).to.eql('hello');
done();
}
});
});
});
});
2 changes: 2 additions & 0 deletions test/browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ if (global.ArrayBuffer) {
if (Blob) {
require('./blob.js');
}

require('./base64_object.js');

0 comments on commit e53e9f5

Please sign in to comment.