2012-11-09 69 views
3

我上的Node.js应用程序的工作,我需要序列化和反序列化在.thrift文件中定义的结构的情况下,类似如下:序列化,反序列化与Apache在节俭的NodeJS

struct Notification { 
    1: string subject, 
    2: string message 
} 

现在这是在Java中容易可行的,根据在http://www.gettingcirrius.com/2011/03/rabbitmq-with-thrift-serialization.html教程:

Notification notification = new Notification(); 
    TDeserializer deserializer = new TDeserializer(); 
    deserializer.deserialize(notification, serializedNotification); 
    System.out.println("Received "+ notification.toString()); 

但我怎么也找不到这是使用节俭的图书馆的NodeJS完成。任何人都可以帮忙吗?

回答

5

好吧,研究浪费了大量的时间和尝试不同的解决方案后,我终于来到了答案我自己的问题:

//SERIALIZATION: 
var buffer = new Buffer(notification); 
var transport = new thrift.TFramedTransport(buffer); 
var binaryProt = new thrift.TBinaryProtocol(transport); 
notification.write(binaryProt); 

其中通知我想序列化对象。此时,可以在transport.outBuffers字段中找到字节数组: var byteArray = transport.outBuffers;

反序列化:

var tTransport = new thrift.TFramedTransport(byteArray); 
var tProtocol = new thrift.TBinaryProtocol(tTransport); 
var receivedNotif = new notification_type.Notification(); 
receivedNotif.read(tProtocol); 

假设以下行已添加到index.js文件从库的NodeJS为节俭:

exports.TFramedTransport = require('./transport').TFramedTransport; 
exports.TBufferedTransport = require('./transport').TBufferedTransport; 
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol; 
+0

如果你想在浏览器的JavaScript反序列化,看看:[thrift-js](https://github.com/amalakar/thrift-js)。回购包含thrift node.js模块中的文件,但修改后可在浏览器和示例中使用。 –

+2

'新缓冲区(通知)'应该如何工作?你传递一个对象到构造函数中,Node中没有这样的重载。你也不需要修改节俭的'index.js',因为它只是'require('thrift/lib/thrift/transport')'等。 –