我正在尝试使用 node_redis 从 node.js 使用 redis 的 ZINTERSTORE 命令:
//node.js server code
var redis = require("redis");
var client = redis.createClient();
// ... omitted code ...
exports.searchImages = function(tags, page, callback){
//tags = ["red", "round"]
client.ZINTERSTORE("tmp", tags.length, tags.join(' '), function(err, replies){
//do something
});
}
但是调用 client.ZINTERSTORE 会抛出错误:[错误:ERR 语法错误]。将标签作为数组传递(而不是使用 tags.join(' '))会引发相同的错误。
在哪里可以找到此命令的正确语法? node_redis 的源代码隐藏在 javascript 解析器中,但如果不“单步执行”代码就很难看到发生了什么。有没有一种使用 node.js 逐步调试的好方法?
最佳答案
有多种方法可以使用 node.js 调试 Redis 客户端。
首先,您可以依靠 Redis 监视器功能来记录 Redis 服务器收到的每条命令:
> src/redis-cli monitor
OK
1371134499.182304 [0 172.16.222.72:51510] "info"
1371134499.185190 [0 172.16.222.72:51510] "zinterstore" "tmp" "2" "red,round"
您可以看到 Redis 收到的 zinterstore 命令格式错误。
然后,您可以通过在脚本中添加以下行来激活 node_redis 的 Debug模式:
redis.debug_mode = true;
运行时会输出Redis协议(protocol):
Sending offline command: zinterstore
send ncegcolnx243:6379 id 1: *4
$11
zinterstore
$3
tmp
$1
2
$9
red,round
send_command buffered_writes: 0 should_buffer: false
net read ncegcolnx243:6379 id 1: -ERR syntax error
然后,您可以使用 node.js debugger .按照以下方式在代码中放置调试器断点:
function search(tags, page, callback) {
debugger; // breakpoint is here
client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
console.log(err);
console.log(replies);
callback('ok')
});
}
然后您可以在 Debug模式下使用 Node 启动脚本:
$ node debug test.js
< debugger listening on port 5858
connecting... ok
break in D:\Data\NodeTest\test.js:1
1 var redis = require("redis");
2 var client = redis.createClient( 6379, "ncegcolnx243" );
3
debug> help
Commands: run (r), cont (c), next (n), step (s), out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb),
watch, unwatch, watchers, repl, restart, kill, list, scripts, breakOnException, breakpoints, version
debug> cont
break in D:\Data\NodeTest\test.js:8
6 function search(tags, page, callback) {
7
8 debugger;
9 client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
10 console.log(err);
... use n(ext) and s(tep) commands ...
通过单步执行代码,您将意识到命令数组不正确,因为标记被序列化并作为唯一参数处理。
按如下方式更改代码将解决问题:
var cmd = [ "tmp", tags.length ];
client.zinterstore( cmd.concat(tags), function(err, replies) {
...
});
关于node.js - ZINTERSTORE 与 node_redis 的动态参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17087856/