7

I'm making a game server and I would like to type commands after I run the server from SSH. For example: addbot, generatemap, kickplayer, etc.

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?

1 Answer 1

12

You can use process.stdin like this:

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:

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);
})
Sign up to request clarification or add additional context in comments.

3 Comments

"quit" command doesn't work :P It seems like "text" variable has this text + "enter" ;) How to delete this enter?
@Ludwik11 use .trim()
Wow, great, and when you combine with eval() you can execute directly JS. so cool! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.