How to store a binary object in redis using node?

我是研究僧i 提交于 2019-12-03 01:39:53

The problem is that the Redis client for Node converts responses to JavaScript strings by default.

I solved this by setting the return_buffers option to true when creating the client.

var client = redis.createClient(7000, '127.0.0.1', {'return_buffers': true});

See here for more details.

I was unable to figure out how to get the binary string to store.

Here is my workaround:

Where data is the data in base64 string

client.set(count,data);

to serve the data:

 client.get(last,function(err,reply){
   var data = reply;
   response.writeHead(200, {"Content-Type": "image/png"});
   var buff=new Buffer(data,'base64');
   response.end(buff);
});

This isn't ideal since you have to do the conversion every time, but it seem to work.

The problem with return_buffers is when you are not using pure buffer data's then you'll have to do something to convert other buffers to strings. While detect_buffers could be an option it is too unreliable.

If you don't mind the extra computing cycles. You could also try:

// convert your buffer to hex string
client.set(key, mybuffer.toString('hex'));
// create a new buffer from hex string
client.get(key, function (err, val) {
   var bin = new Buffer(val, 'hex');
});

What worked for me is to use data.toString('binary') if it is a Buffer. Also make sure not to reinterpret it as utf-8, but also as binary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!