问题
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...
According to https://github.com/joyent/node/blob/master/lib/repl.js the signature is
function(code, context, file, cb) {
//code
cb(err, result);
}
Let me know if there is a more appropriate solution.
回答1:
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.
You need to do is change the argument list of the callback given to repl.start
to:
function(cmd, context, file, callback) {
or use the common:
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();
来源:https://stackoverflow.com/questions/10713247/node-repl-eval-callback