如果没有exernal模块,如何与redis交流?

时间:2016-08-27 09:39:49

标签: javascript node.js npm redis

我想知道节点redis wrapper如何与RESP(REdis序列化协议)数据库通信。

一个例子

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?
}

1 个答案:

答案 0 :(得分:0)

因此RESP是基于TCP连接的纯文本协议。

Node允许您使用builtin net module及其Socket类建立TCP连接。

因此,对于您的示例(请注意:它是一个明显过于简化的版本):

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
}