node.js - Node REPL eval 回调

标签 node.js read-eval-print-loop

我有一个小示例程序http://pastebin.com/5gFkaPgg通过 TCP 向客户端提供 REPL。根据文档http://nodejs.org/api/repl.html我已通过 eval 函数(第 11-13 行)正确设置,但回调对象不是函数。我在文档中误解了什么?

  callback(null,result);
  ^
TypeError: object is not a function

无法回答我自己的问题...

根据https://github.com/joyent/node/blob/master/lib/repl.js 签名是

function(code, context, file, cb) {
  //code
  cb(err, result);
}

如果有更合适的解决方案,请告诉我。

最佳答案

错误和签名告诉我,回调是作为其参数(code, context, file, cb)给出的,但预期是其参数(code, cb) 因此 context 绑定(bind)到 cb 并且由于 context 不是函数,因此产生了错误。

您需要做的是将提供给 repl.start 的回调的参数列表更改为:

function(cmd, context, file, callback) {

或者使用通用的:

function(cmd) {
  var callback = arguments[arguments.length-1]; // get the last argument

使用第二个选项的代码,因为它没有引入新名称:

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();

关于node.js - Node REPL eval 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10713247/

相关文章:

node.js - 如何进行行搜索?

java - Clojure REPL 未在 Windows 命令提示符下启动

Node.js 解释 REPL 中的错误?

swift - "xcrun swift"用于结果的方法/属性是什么?

javascript - 如何在 Nodejs REPL 中隐藏 process.stdout.write() 的返回值?

node.js - 如何处理expressjs中间件请求。 dropzone 发出的 POST 请求仍待处理

javascript - react /jquery : redirecting to another URL with built query string

bash - 如何用行缓冲提示包装命令?

node.js - 隔离 Node.js 中模块之间的全局更改

node.js - MongoDB 保存用户时电子邮件和密码无效