Last active
October 20, 2020 12:20
-
-
Save nadalizadeh/6811aec66c258aae90f72df638d410d2 to your computer and use it in GitHub Desktop.
Read and Write Thrift Encoded Buffers in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var thrift = require('thrift') | |
var ttypes = require('./gen-nodejs/serialization_types') // Replace it with your own ttypes generated file | |
// Use frame transport to read | |
var Transport = thrift.TFramedTransport | |
var Protocol = thrift.TCompactProtocol | |
// packet.payload is the thrift encoded data we have received | |
var bufTrans = new Transport(packet.payload) | |
var myprot = new Protocol(bufTrans) | |
var chatMsg = new ttypes.ChatMessageData() // Replace ChatMessageData with your own thrift structure | |
chatMsg.read(myprot) | |
// Use the decoded data | |
console.log(' -> User: ' + chatMsg.player.id + ' Name: ' + chatMsg.player.name + ' Message: ' + chatMsg.message) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var thrift = require('thrift') | |
var ttypes = require('./gen-nodejs/serialization_types') // Replace it with your own ttypes generated file | |
// Use buffered transport to write | |
var Transport = thrift.TBufferedTransport | |
var Protocol = thrift.TCompactProtocol | |
var myBuf = new Buffer([]) | |
var buftra = new Transport(myBuf, function (outBuf) { | |
myBuf = Buffer.concat([myBuf, outBuf]) | |
}) | |
var myprot = new Protocol(buftra) | |
// replace ChatMessageData with your own thrift structure | |
var chatMsg = new ttypes.ChatMessageData({ | |
message: 'Hello World', | |
timestamp: 123456, | |
player: new ttypes.PlayerRecord({ | |
id: 99004, | |
name: 'Test-Player' | |
}) | |
}) | |
// Write and flush buffers | |
// The callback above will be called and fill myBuf | |
chatMsg.write(myprot) | |
myprot.flush() | |
buftra.flush() | |
// Thrift encoded buffer is ready to use, save or transport | |
console.log(myBuf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment