Node REPL eval Callback

烈酒焚心 提交于 2019-12-23 03:22:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!