节点 REPL 评估回调 [英] Node REPL eval Callback
问题描述
我有一个小示例程序 http://pastebin.com/5gFkaPgg 为客户端提供 REPL通过 TCP.根据文档 http://nodejs.org/api/repl.html 我通过 eval函数(第 11-13 行)正确设置,但回调对象不是函数.我在文档中误解了什么?
I have a small sample program http://pastebin.com/5gFkaPgg that serves a REPL to a client over TCP. Acording to the docs http://nodejs.org/api/repl.html I have by eval function (lines 11-13) setup correctly, but the callback object is not a function. What am I misinterpreting in the docs?
callback(null,result);
^
TypeError: object is not a function
无法回答我自己的问题...
Can't Answer my own question...
根据https://github.com/joyent/node/blob/master/lib/repl.js签名是
function(code, context, file, cb) {
//code
cb(err, result);
}
如果有更合适的解决方案,请告诉我.
Let me know if there is a more appropriate solution.
推荐答案
错误和签名告诉我回调是作为参数给出的 (code, context, file, cb)
但预期作为它的参数 (code, cb)
因此 context
被绑定到 cb
并且 context
不是一个函数,产生了错误.
The error and the signature tells me that the callback was given as its arguments (code, context, file, cb)
but expected as its arguments (code, cb)
and thus context
was bound to cb
and as context
is not a function, the error was produced.
您需要做的是将给repl.start
的回调的参数列表更改为:
You need to do is change the argument list of the callback given to repl.start
to:
function(cmd, context, file, callback) {
或使用通用:
function(cmd) {
var callback = arguments[arguments.length-1]; // get the last argument
带有第二个选项的代码,因为它没有引入新名称:
Code with the second option as it introduces no new names:
var net = require('net');
var repl = require('repl');
function main() {
var clients = [];
net.createServer(function(socket) {
clients.push(socket);
repl.start(">", socket, function(cmd) {
var callback = arguments[arguments.length-1];
var result = cmd;
callback(null,result);
});
socket.on('end',function() {
clients.splice(clients.indexOf(socket));
});
}).listen(8000);
}
main();
这篇关于节点 REPL 评估回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!