Skip to content

Commit 99ebb0d

Browse files
echopiclaude
andcommitted
fix: detect port-in-use before starting (#1234)
Add a port availability pre-check before starting the whistle server. When the port is already in use, output a friendly error message to stderr and exit, instead of crashing with an uncaught exception. Compared to the previous attempt (PR #1313), this fix: - Works for all startup modes, not just cluster mode - Uses console.error + process.exit instead of throw in async callback - Does not include unrelated changes (cluster mode, config loading, etc.) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 6ff0305 commit 99ebb0d

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

index.js

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ if (!net._normalizeConnectArgs) {
6767
};
6868
}
6969

70+
function checkPortAvailable(port, host, cb) {
71+
var server = net.createServer();
72+
server.unref();
73+
server.on('error', cb);
74+
server.listen(port, host || '0.0.0.0', function() {
75+
server.close(cb);
76+
});
77+
}
78+
7079
module.exports = function(options, callback) {
7180
if (typeof options === 'function') {
7281
callback = options;
@@ -75,6 +84,22 @@ module.exports = function(options, callback) {
7584
if (options && options.debugMode) {
7685
env.PFORK_MODE = 'bind';
7786
}
78-
require('./lib/config').extend(options);
79-
return require('./lib')(callback);
87+
var conf = require('./lib/config').extend(options);
88+
if (options && options.server) {
89+
return require('./lib')(callback, options.server);
90+
}
91+
checkPortAvailable(conf.port, conf.host, function(err) {
92+
if (err) {
93+
if (err.code === 'EADDRINUSE') {
94+
var addr = (conf.host ? conf.host + ':' : '') + conf.port;
95+
console.error('[!] Port ' + addr + ' is already in use.');
96+
console.error('[i] Use -p <port> to specify another port.');
97+
} else {
98+
console.error(err.stack || err.message || err);
99+
}
100+
process.exit(1);
101+
return;
102+
}
103+
require('./lib')(callback);
104+
});
80105
};

0 commit comments

Comments
 (0)