简体   繁体   English

运行Node.js程序时保持对控制台的访问

[英]Maintain access to console while running Node.js program

Can I send commands to Node.js process running a .js script? 我可以向运行.js脚本的Node.js进程发送命令吗? Currently I just run node and paste my code into console. 目前,我只运行node并将代码粘贴到控制台中。 It's not very convenient. 这不是很方便。

You can start a repl server (that has access to the script's scope) like this: 您可以像这样启动一个repl服务器(可以访问脚本的作用域):

var repl = require('repl'),
    net = require('net');

var REPL_PORT = 2323;

var replServer = net.createServer(function(sock) {
  repl.start({
    prompt: 'myrepl> ',
    input: sock,
    output: sock,
    eval: function(cmd, context, filename, callback) {
      var ret, err;
      try {
        ret = eval(cmd);
      } catch (e) {
        err = e;
      }
      if (err)
        callback(err);
      else
        callback(null, ret);
    }
  }).on('exit', function() {
    sock.end();
  });
});
replServer.on('error', function(err) {
  console.log('REPL error: ' + err);
});
replServer.on('close', function(had_err) {
  console.log('REPL shut down ' + (had_err ? 'due to error' : 'gracefully'));
});
replServer.on('listening', function() {
  console.log('REPL listening on port ' + REPL_PORT);
});
replServer.listen(REPL_PORT, '127.0.0.1');

Then just telnet to localhost at port 2323 and you'll get a repl prompt that you can type stuff into and poke at variables and such that are defined in your script. 然后只需在端口2323上通过telnet到localhost,您将得到一个repl提示符,您可以在脚本中定义的变量和类似的内容键入内容并戳入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM