UNPKG

express-port-switcher

Version:

A smart port management tool that automatically finds and forwards to available ports when preferred ports are in use

64 lines 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findNextAvailablePort = exports.isPortAvailable = exports.PortSwitcher = void 0; const portUtils_1 = require("./lib/portUtils"); class PortSwitcher { constructor(options = {}) { this.actualPort = null; this.server = null; this.preferredPort = options.preferredPort || 3000; this.maxAttempts = options.maxAttempts || 100; this.onPortSwitch = options.onPortSwitch; } /** * Start the Express app on the preferred port, or switch to next available port if occupied * @param app Express application instance * @returns Promise resolving to the actual port the server is running on */ async listen(app) { try { // Find an available port starting from the preferred port const availablePort = await (0, portUtils_1.findNextAvailablePort)(this.preferredPort, this.maxAttempts); if (!availablePort) { throw new Error('No available ports found'); } // Start the server on the available port await new Promise((resolve, reject) => { this.server = app.listen(availablePort, () => { this.actualPort = availablePort; if (availablePort !== this.preferredPort && this.onPortSwitch) { this.onPortSwitch(this.preferredPort, availablePort); } resolve(); }); this.server.on('error', reject); }); return availablePort; } catch (error) { // Clean up resources in case of error await this.close(); throw error; } } /** * Get the actual port the server is running on */ getActualPort() { return this.actualPort; } /** * Close the server */ async close() { if (this.server) { this.server.close(); } } } exports.PortSwitcher = PortSwitcher; // Export utility functions as well var portUtils_2 = require("./lib/portUtils"); Object.defineProperty(exports, "isPortAvailable", { enumerable: true, get: function () { return portUtils_2.isPortAvailable; } }); Object.defineProperty(exports, "findNextAvailablePort", { enumerable: true, get: function () { return portUtils_2.findNextAvailablePort; } }); //# sourceMappingURL=index.js.map