Node.js Destroyable Server

1.1.1 · active · verified Sun Apr 19

Destroyable-Server, currently at version 1.1.1, is a compact Node.js module designed to enhance the `net.Server` API by providing a reliable and immediate mechanism to terminate all active client connections. When `server.close()` is invoked, it merely ceases to accept new connections, often leaving existing ones open and preventing the Node.js process from exiting cleanly. This library introduces a `destroy()` method to server instances via its `makeDestroyable` utility, which not only stops listening but also forcibly closes every tracked socket. This capability is critical for scenarios requiring rapid server restarts, robust test suite teardowns, or graceful application shutdowns. It works across various `net.Server` subclasses, including HTTP and TLS, and uniquely offers a promise-based interface for awaiting complete connection termination, differentiating it from `server.closeIdleConnections()` which might miss active connections or not be universally available. The project maintains a stable, low-cadence release cycle, reflecting its focused utility and role as part of HTTP Toolkit.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a Node.js TCP server, making it destroyable, and then gracefully shutting it down by forcibly closing all active connections after a delay.

import { createServer } from 'net';
import { makeDestroyable } from 'destroyable-server';

const PORT = process.env.PORT ?? 8000;

// Create a basic TCP server
let server = createServer((socket) => {
  console.log('Client connected.');

  socket.write('Hello from destroyable-server!\n');
  socket.on('end', () => {
    console.log('Client disconnected.');
  });

  // Example: close connection after 5 seconds
  setTimeout(() => {
    if (!socket.destroyed) {
      socket.end('Server closing connection.\n');
    }
  }, 5000);
});

// Make the server destroyable
server = makeDestroyable(server);

server.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}.`);
});

// Simulate a shutdown after 10 seconds
setTimeout(async () => {
  console.log('Initiating server shutdown...');
  try {
    await server.destroy();
    console.log('Server and all connections destroyed successfully.');
  } catch (error) {
    console.error('Error during server destruction:', error);
  }
  // In a real application, you might then exit the process: process.exit(0);
}, 10000);

view raw JSON →