Here is the thing - I want to store native JS (node.js) objects (flash sockets references) in redis under a certain key. When I do that with simple client.set()
it's stored as a string. When I try to get value I get [object Object]
- just a string.
Any chance to get this working? Here's my code:
addSocket : function(sid, socket) { client.set(sid, socket); }, getSocket : function(sid) { client.get(sid, function(err, reply) { // cant't get an object here. All I get is useless string }); },
Object Storing Procedure. 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.
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.
Redis has support for storing multiple data structures and data types , including strings, lists, hashes, sets, and sorted sets. Supported data structures give Redis the versatility for many use cases. Redis is best in situations that require data to be retrieved and delivered to the client in the least amount of time.
Since the socket is of type Object
, you need to convert the object to a string before storing and when retrieving the socket, need to convert it back to an object.
You can use
JSON.stringify(socket)
to convert to a string and
JSON.parse(socketstr)
to convert back to an object.
Edit:
Since the release of version 2.0.0
, we are able to store objects as hashes into Redis.
client.hmset("hosts", "mjr", "1", "another", "23", "home", "1234"); client.hgetall("hosts", function (err, obj) { console.dir(obj); });
https://redis.io/commands/hset
https://github.com/NodeRedis/node_redis
Downvoters: the context here is SET command and ability to store arbitrary objects.
No, you can't do that. You should accept the fact that Redis stores everything as a string (the protocol is text-based, after all). Redis may perform some optimizations and convert some values to integers, but that's its business, not yours.
If you want to store arbitrary objects in Redis, make sure that you serialize them before saving and de-serialize after retrieving.
I'm not sure if you can do that with socket objects, though. They simply describe a system resource (an open connection), after all (TCP sockets, for example). If you manage to serialize the description and deserialize it on another machine, that other machine won't have the connection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With