0

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):

  • stop
  • reload
  • restart
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

3

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)

Mauricio Poppe
  • 4,817
  • 1
  • 22
  • 30