Skip to content

Commit

Permalink
Fail runServer quickly if the port is not available
Browse files Browse the repository at this point in the history
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
  • Loading branch information
motiz88 authored and facebook-github-bot committed Apr 28, 2022
1 parent 72e3118 commit 6d9623e
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/metro/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const http = require('http');
const https = require('https');
const {getDefaultConfig, loadConfig, mergeConfig} = require('metro-config');
const {InspectorProxy} = require('metro-inspector-proxy');
const net = require('net');
const {parse} = require('url');
const ws = require('ws');

Expand Down Expand Up @@ -225,6 +226,8 @@ exports.runServer = async (
websocketEndpoints = {},
}: RunServerOptions,
): Promise<HttpServer | HttpsServer> => {
await earlyPortCheck(host, config.server.port);

if (secure != null || secureCert != null || secureKey != null) {
// eslint-disable-next-line no-console
console.warn(
Expand Down Expand Up @@ -463,3 +466,17 @@ exports.attachMetroCli = function (
}
return yargs;
};

async function earlyPortCheck(host: void | string, port: number) {
const server = net.createServer(c => c.end());
try {
await new Promise((resolve, reject) => {
server.on('error', err => {
reject(err);
});
server.listen(port, host, undefined, () => resolve());
});
} finally {
await new Promise(resolve => server.close(() => resolve()));
}
}

0 comments on commit 6d9623e

Please sign in to comment.