Get Off My Lawn
Get Off My Lawn

Reputation: 36299

http.listen() accept terminal commands while running

I have the following in my script:

var server = http.createServer(handleRequest);
server.listen(3000, function(err){
    console.log(err || 'Server listening on 3000');
});

When I execute the script in the terminal:

nodejs file.js

It runs in an endless loop until I hit Ctrl + C. Is it possible to enter custom commands while the process is running since it doesn't go back to the default terminal? I would like to add a few custom commands to my app such as (but not limited to):

Upvotes: 0

Views: 80

Answers (1)

Mauricio Poppe
Mauricio Poppe

Reputation: 4876

You can use the process.stdin stream (the data event is fired on newline):

var http = require('http');

var server = http.createServer(function (err, req, res) {
  // ...
});
server.listen(3000, function(err){
    console.log(err || 'Server listening on 3000');
});

var commands = {
  stop: function () {
    console.log('> stop');
  },
  start: function () {
    console.log('> start')
  },
  restart: function () {
    console.log('> restart')
  }
}

process.stdin.on('data', function (data) {
  data = (data + '').trim().toLowerCase();
  if (data in commands) {
    commands[data]();
  }
});

Just for reference nodemon does something similar (it restarts the server when rs is entered source)

Upvotes: 3

Related Questions