Mark Mark - 3 months ago 16
Javascript Question

How comunicate with redis without exernal modules?

I want know how node redis wrapper comunicate with RESP (REdis Serialization Protocol) database.

an example

const redis = function(uri) {
this.client = '' // how connect with redis uri redis://localhost:6379
}

redis.prototype.set = (key, value, callback) => {
// how comunicate with redis and set some value?
}

Answer

So the RESP is a plain-text protocol based on a TCP connection.

Node allows you to make TCP connections using the builtin net module and its Socket class.

So for your example (note: it's a clearly oversimplified version):

var net = require('net'); // builtin since Node 0.3.4

const redis = function(uri) {
  var host = getHostFromUri(uri), port = getPortFromUri(uri)
  this.client = new net.Socket()
  this.client.connect(port, host, function() { ... })
  this.client.on('data', function(msg) {
    if(this.responseHandler) this.responseHandler(msg)
  })
}

redis.prototype.set = function(key, value, callback) {
  // assuming the connection was successful
  this.client.write("SET " + key + " " + value + "\r\n")
  this.responseHandler = callback
}
Comments