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



我正在制作一个游戏服务器,我想在从 SSH 运行服务器后键入命令。例如:addbot,generatemap,kickplayer等。

就像在半条命或任何其他游戏服务器中一样。如何使 Node.js 监听我的命令并仍然保持服务器在 SSH 中运行?

你可以像这样使用 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();
}

否则,您可以使用帮助程序库(如提示 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);
})

最新更新