Monday, 24 April 2017

Node/Express server with foolproof error handling and graceful shutdown

The more I read about all the issues with how to start a node/express server and handle errors and shutdown properly, the more I get confused. Below is the basic script I usually use. I would like someone with deep knowledge of this issue to critique this script, post a best practice server code here, or point me to a resource that provides that.

var express = require('express');

var sockets = [];
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);

var port = 7000;
var app = express();
var server = app.listen(port, function () {
    console.log(`app listening on port ${port}`);
})
.on("connection", onConnection)
.on("listening", onListening)
.on("error", onError)
.on("close", onClose);


var cleanup = function () {
    server.close(function () {
        console.log("Closed out remaining connections.");
        process.exit();
    });
    sockets.forEach(function (socket) {
        socket.destroy();
    });

    setTimeout(function () {
        console.log("Could not close connections in time, forcing shut down");
        process.exit(1);
    }, 30 * 1000);
}

function onConnection(socket) {
  sockets.push(socket);
}

function onError(error) {
  if (error.syscall !== 'listen') throw error;

  var bind = typeof port === 'string'? 'Pipe ' + port : 'Port ' + port;

  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'? 'pipe ' + addr : 'port ' + addr.port;
  console.log('Listening on ' + bind);
}

function onClose() {}



via prmph

No comments:

Post a Comment