How to implement console commands while the server is running in Node.js

I am creating a game server and I would like to enter commands after starting the server from SSH. For example: addbot, generatemap, kickplayer, etc.

Both in Half-Life and in any other game server. How can I make Node.js listen to my commands and still keep the server in SSH?

+5
source share
1 answer

You can use process.stdin as follows:

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 auxiliary libraries such as prompt https://github.com/flatiron/prompt , which allows you to do this:

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);
})
+10
source

All Articles