Skip to content

Instantly share code, notes, and snippets.

@alv-alvarez
Last active October 17, 2020 22:55
Show Gist options
  • Save alv-alvarez/86d2c1b69d88019b841edc5308fee952 to your computer and use it in GitHub Desktop.
Save alv-alvarez/86d2c1b69d88019b841edc5308fee952 to your computer and use it in GitHub Desktop.
Nodejs Notes

By Julián Duque

Recomendations

  • Run more than one process
  • Monitor your processes: Restart with native process monitoring Linux: systemd or upstart, Docker: restart. Last resource use pm2 (not recommend)
  • Graceful shutdowns
  • Logging: pino o winston
  • Add health check route
app.get('/_health', (req, res) => {
  res.status(200).send('ok')
})

Module for incorporate in new project

function terminate (server, options = { coredump: false, timeout: 500 }) {
  // Exit function
  const exit = code => {
    options.coredump ? process.abort() : process.exit(code)
  }

  return (code, reason) => (err, promise) => {
    if (err && err instanceof Error) {
    // Log error information, use a proper logging library here :)
    console.log(err.message, err.stack)
    }

    // Attempt a graceful shutdown
    server.close(exit)
    setTimeout(exit, options.timeout).unref()
  }
}

module.exports = terminate

Using example

const http = require('http')
const terminate = require('./terminate')
const server = http.createServer(...)

const exitHandler = terminate(server, {
  coredump: false,
  timeout: 500
})

process.on('uncaughtException', exitHandler(1, 'Unexpected Error'))
process.on('unhandledRejection', exitHandler(1, 'Unhandled Promise'))
process.on('SIGTERM', exitHandler(0, 'SIGTERM'))
process.on('SIGINT', exitHandler(0, 'SIGINT'))

Aditional Library

  • @godaddy/terminus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment