Skip to content

Commit 6d9623e

Browse files
motiz88facebook-github-bot
authored andcommittedApr 28, 2022
Fail runServer quickly if the port is not available
Summary: Adds an early check that the Metro server port is available before trying to set up the bundler. This allows integrators to give faster feedback to the user in this case. Changelog: * **Fix**: Fail `runServer` quickly if the port is not available. Reviewed By: GijsWeterings Differential Revision: D35849394 fbshipit-source-id: ea01c47a0ff78783670113ede6d8e86b05e76b1e
1 parent 72e3118 commit 6d9623e

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
 

‎packages/metro/src/index.js

+17
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ const http = require('http');
3737
const https = require('https');
3838
const {getDefaultConfig, loadConfig, mergeConfig} = require('metro-config');
3939
const {InspectorProxy} = require('metro-inspector-proxy');
40+
const net = require('net');
4041
const {parse} = require('url');
4142
const ws = require('ws');
4243

@@ -225,6 +226,8 @@ exports.runServer = async (
225226
websocketEndpoints = {},
226227
}: RunServerOptions,
227228
): Promise<HttpServer | HttpsServer> => {
229+
await earlyPortCheck(host, config.server.port);
230+
228231
if (secure != null || secureCert != null || secureKey != null) {
229232
// eslint-disable-next-line no-console
230233
console.warn(
@@ -463,3 +466,17 @@ exports.attachMetroCli = function (
463466
}
464467
return yargs;
465468
};
469+
470+
async function earlyPortCheck(host: void | string, port: number) {
471+
const server = net.createServer(c => c.end());
472+
try {
473+
await new Promise((resolve, reject) => {
474+
server.on('error', err => {
475+
reject(err);
476+
});
477+
server.listen(port, host, undefined, () => resolve());
478+
});
479+
} finally {
480+
await new Promise(resolve => server.close(() => resolve()));
481+
}
482+
}

0 commit comments

Comments
 (0)
Please sign in to comment.