简体   繁体   English

如何在Node.js中运行服务器时实现控制台命令

[英]How to implement console commands while server is running in Node.js

I'm making a game server and I would like to type commands after I run the server from SSH. 我正在制作一个游戏服务器,我想在从SSH运行服务器后输入命令。 For example: addbot, generatemap, kickplayer, etc. 例如:addbot,generatemap,kickplayer等。

Like in Half-life or any other gameserver. 就像半条命或任何其他游戏服务器一样。 How can I make Node.js listen to my commands and still keep the server running in SSH? 如何让Node.js监听我的命令并仍然使服务器在SSH中运行?

You can use process.stdin like this: 您可以像这样使用process.stdin

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (text) {
  console.log(text);
  if (text.trim() === 'quit') {
    done();
  }
});

function done() {
  console.log('Now that process.stdin is paused, there is nothing more to do.');
  process.exit();
}

Otherwise, you can use helper libraries like prompt https://github.com/flatiron/prompt which lets you do this: 否则,你可以使用帮助库,如提示https://github.com/flatiron/prompt ,它可以让你这样做:

var prompt = require('prompt');

// Start the prompt
prompt.start();

// Get two properties from the user: username and email
prompt.get(['username', 'email'], function (err, result) {

  // Log the results.
  console.log('Command-line input received:');
  console.log('  username: ' + result.username);
  console.log('  email: ' + result.email);
})

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

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