Skip to content

Commit

Permalink
Replace get-port (#2242)
Browse files Browse the repository at this point in the history
  • Loading branch information
soulgalore authored Jan 5, 2025
1 parent 89cc995 commit a31e04d
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 27 deletions.
12 changes: 3 additions & 9 deletions lib/core/engine/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { arch as _arch } from 'node:os';
import intel from 'intel';
import merge from 'lodash.merge';
import getPort, { portNumbers } from 'get-port';
import { execaCommand as command } from 'execa';
import get from 'lodash.get';
import { StorageManager } from '../../support/storageManager.js';
Expand Down Expand Up @@ -31,6 +30,7 @@ import {
loadScript,
loadPageCompleteScript
} from '../../support/engineUtils.js';
import { getAvailablePort } from '../../support/getPort.js';
const log = intel.getLogger('browsertime');
const defaults = {
scripts: [],
Expand Down Expand Up @@ -67,19 +67,13 @@ export class Engine {
async start() {
const options = this.options;

options.devToolsPort = await getPort({
port: portNumbers(9222, 9350),
host: '127.0.0.1'
});
options.devToolsPort = await getAvailablePort([9222, 9350]);

log.debug(
`Preparing port ${options.devToolsPort} for devtools on Chrome/Edge`
);

options.safariDriverPort = await getPort({
port: portNumbers(1234, 2000),
host: '127.0.0.1'
});
options.safariDriverPort = await getAvailablePort([1234, 2000]);

if (options.browser === 'safari' && options.safari.ios && options.video) {
await IOSRecorder.activate();
Expand Down
25 changes: 25 additions & 0 deletions lib/support/getPort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createServer } from 'node:net';

export async function getAvailablePort(portRange, host = '127.0.0.1') {
const startPort = portRange[0];
const endPort = portRange[1];

for (let port = startPort; port <= endPort; port++) {
if (await isPortAvailable(port, host)) {
return port;
}
}

throw new Error(`No available ports found in range ${startPort}-${endPort}`);
}

function isPortAvailable(port, host) {
return new Promise(resolve => {
const server = createServer();
server.unref();
server.on('error', () => resolve(false));
server.listen(port, host, () => {
server.close(() => resolve(true));
});
});
}
17 changes: 0 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"execa": "9.5.2",
"fast-stats": "0.0.7",
"ff-test-bidi-har-export": "0.0.17",
"get-port": "7.1.0",
"intel": "1.2.0",
"lodash.get": "4.4.2",
"lodash.merge": "4.6.2",
Expand Down

0 comments on commit a31e04d

Please sign in to comment.