简体   繁体   中英

Maintain access to console while running Node.js program

Can I send commands to Node.js process running a .js script? Currently I just run node and paste my code into console. It's not very convenient.

You can start a repl server (that has access to the script's scope) like this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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