Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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?

like image 695
Nick Avatar asked May 03 '12 09:05

Nick


People also ask

How do I open the console in node JS?

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC. You can now test pretty much any Node. js/JavaScript expression in REPL.

Can you console log in node JS?

log() function from console class of Node. js is used to display the messages on the console. It prints to stdout with newline. Parameter: This function contains multiple parameters which are to be printed.

What is exec () in node JS?

The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .


1 Answers

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);
})
like image 171
250R Avatar answered Nov 04 '22 03:11

250R