Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a binary object in redis using node?

Tags:

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

like image 492
SamFisher83 Avatar asked Dec 22 '13 17:12

SamFisher83


People also ask

How do I store an object in Redis?

In the Redis, Everything can be stored as only key-value pair format. Key must be unique and storing an object in a string format is not a good practice anyway. Objects are usually stored in a binary array format in the databases. Here we are also going to use the binary array format to store the object.

How does Redis store data in node JS?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.


1 Answers

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.

like image 66
mb. Avatar answered Sep 19 '22 12:09

mb.