Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created April 9, 2017 06:58
Show Gist options
  • Save twolfson/4f86ae8272e324c140056338d1a0fbc5 to your computer and use it in GitHub Desktop.
Save twolfson/4f86ae8272e324c140056338d1a0fbc5 to your computer and use it in GitHub Desktop.
Proof of concept exploring protobuf in the browser
node_modules/
// Load in our dependencies
var protobuf = require('protobufjs');
// Define our protobuf type
// Inspired by: https://github.com/dcodeIO/protobuf.js/blob/6.7.3/examples/streaming-rpc.js
var root = protobuf.Root.fromJSON({
nested: {
Message: {
fields: {
content: {
type: 'string',
id: 1
},
timestamp: {
type: 'string',
id: 2
}
}
}
}
});
var Message = root.lookup('Message');
// Define and run our main function
function main() {
var obj = {
content: 'Hello World!',
timestamp: 'NOW',
};
var msg = Message.encode(obj).finish();
console.log(msg);
console.log(msg.toString('utf8'));
console.log('protobuf', msg.length);
console.log('');
// DEV: We don't save much with a flat array but I guess we save some space and
// I wonder what decryption cost is on 500kb...
// They have a benchmark, checking it out now...
// https://github.com/dcodeIO/protobuf.js/blob/6.7.3/bench/index.js
var jsonStr = JSON.stringify([obj.content, obj.timestamp]);
console.log(jsonStr);
console.log(jsonStr.toString('utf8'));
console.log('json', jsonStr.length);
}
main();
{
"name": "gist-protobuf-explore",
"version": "1.0.0",
"description": "Proof of concept exploring protobuf in the browser",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Todd Wolfson <[email protected]> (http://twolfson.com/)",
"license": "Unlicense",
"dependencies": {
"protobufjs": "~6.7.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment