如何使用gzip解压缩在ruby中压缩的节点数据?

时间:2016-02-17 07:13:57

标签: node.js ruby zlib

我们有一个ruby实例,它通过rabbitmq(bunny和amqplib)向节点实例发送消息,如下所示:

{ :type => data, :data => msg }.to_bson.to_s

这似乎进展得很顺利,但是msg有时很长,我们将它们发送到数据中心。 zlib会有很多帮助。

在红宝石发件人中做这样的事情:

encoded_data = Zlib::Deflate.deflate(msg).force_encoding(msg.encoding)

然后在node:

中读取它
data = zlib.inflateSync(encoded_data)

返回

"\x9C" from ASCII-8BIT to UTF-8

我正在尝试做什么?

1 个答案:

答案 0 :(得分:2)

我不是Ruby dev,所以我会用或多或少的伪代码编写Ruby部分。

Ruby代码(在https://repl.it/BoRD/0在线运行)

require 'json'
require 'zlib'

car = {:make => "bmw", :year => "2003"}

car_str = car.to_json

puts "car_str", car_str

car_byte = Zlib::Deflate.deflate(car_str)
# If you try to `puts car_byte`, it will crash with the following error:
# "\x9C" from ASCII-8BIT to UTF-8
#(repl):14:in `puts'
#(repl):14:in `puts'
#(repl):14:in `initialize'

car_str_dec = Zlib::Inflate.inflate(car_byte)

puts "car_str_dec", car_str_dec
# You can check that the decoded message is the same as the source.

# somehow send `car_byte`, the encoded bytes to RabbitMQ.

节点代码

var zlib = require('zlib');

// somehow get the message from RabbitMQ.
var data = '...';

zlib.inflate(data, function (err, buffer) {
    if (err) {
        // Handle the error.
    } else {
       // If source didn't have any encoding,
       // no need to specify the encoding.
       console.log(buffer.toString());
    }
});

我还建议你坚持使用Node中的异步函数而不是同步替代。