How to store a binary object in redis using node?

Viewed 18912

I am trying to save a binary object in redis and then serve it back as an image.

Here is the code I am using to save the data:

var buff=new Buffer(data.data,'base64');
client.set(key,new Buffer(data.data,'base64'));

Here is the code to dump the data out:

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

});

The first few byte of the data seem to be corrupted. The magic number is incorrect.

Did some experimenting:

when I do the following:

var buff=new Buffer(data.data,'base64');
console.log(buff.toString('binary'));

I get this:

0000000: c289 504e 470d 0a1a 0a00 0000 0d49 4844

when I do this

 var buff=new Buffer(data.data,'base64');
 console.log(buff);

I get the following:

Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00

I am not sure where the c2 is coming from

6 Answers

I found this article on the topic which explains the implications of doing this, which I highly recommend reading before going down this path (regardless of programming language).

http://qnimate.com/storing-binary-data-in-redis/

In summary, since Redis is an in-memory key/value store, you would be wise to not store potentially large values such as images inside Redis as you will quickly use up available memory and degrade the performance of your Redis instance. It is better to store the location of the file in Redis rather than the file itself.

This post is old but just an updated answer. As another answer stated all Node.js Redis libraries return data as utf8 strings because thats what people generally need. Node.js Redis libraries like ioRedis also provide alternatives to fetch data as a buffer. For example redis.getBuffer instead of redis.get.

Related