How to terminate a HTTP server in Node.js?

import {
createServer,
} from 'http';
const server = createServer(() => {});server.listen();const sockets = new Set();server.on('connection', (socket) => {
sockets.add(socket);
server.once('close', () => {
sockets.delete(socket);
});
});
/**
* Forcefully terminates HTTP server.
*/
const close = (callback) => {
for (const socket of sockets) {
socket.destroy();
sockets.delete(socket);
}
server.close(callback);
};
http-terminator gracefully terminates HTTP(S) server.
import http from 'http';
import {
createHttpTerminator,
} from 'http-terminator';
const server = http.createServer();const httpTerminator = createHttpTerminator({
server,
});
await httpTerminator.terminate();
  • it does not monkey-patch Node.js API
  • it immediately destroys all sockets without an attached HTTP request
  • it allows graceful timeout to sockets with ongoing HTTP requests
  • it properly handles HTTPS connections
  • it informs connections using keep-alive that server is shutting down by setting a connection: close header
  • it does not terminate the Node.js process

--

--

--

Tech / Product Founder — building https://contra.com/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gajus Kuizinas

Gajus Kuizinas

Tech / Product Founder — building https://contra.com/

More from Medium

NodeJS with ExpressJS and TypeScript part 1.