Skip to content

Commit

Permalink
refactor(getport): use "node:net" over "node:http"
Browse files Browse the repository at this point in the history
use lowest level server creation possible (should be lower overhead)
  • Loading branch information
hasezoey committed Nov 9, 2023
1 parent 074a5e7 commit c065147
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as getPort from '../index';
import * as http from 'node:http';
import * as net from 'node:net';

// the following tests may fail on systems with actual ports being used in those ranges (20000 to 40000)

Expand Down Expand Up @@ -31,7 +31,7 @@ describe('getport', () => {

it('should return "false" on used port', async () => {
const testPort = 30000;
const blockingServer = http.createServer();
const blockingServer = net.createServer();
blockingServer.unref();
blockingServer.listen(testPort);
await expect(getPort.tryPort(testPort)).resolves.toStrictEqual(false);
Expand Down Expand Up @@ -63,10 +63,8 @@ describe('getport', () => {
const testPort = 23232;
await expect(getPort.getFreePort(testPort)).resolves.toStrictEqual(testPort);

const server = await new Promise<
http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>
>((res) => {
const server = http.createServer();
const server = await new Promise<net.Server>((res) => {
const server = net.createServer();
server.unref();
server.listen(testPort, () => res(server));
});
Expand Down
4 changes: 2 additions & 2 deletions packages/mongodb-memory-server-core/src/util/getport/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as http from 'node:http';
import * as net from 'node:net';

/** Linux min port that does not require root permissions */
export const MIN_PORT = 1024;
Expand Down Expand Up @@ -101,7 +101,7 @@ export function validPort(port: number): number {
*/
export function tryPort(port: number): Promise<boolean> {
return new Promise((res, rej) => {
const server = http.createServer();
const server = net.createServer();

// some engines dont support ".unref"(net / tcp.unref), like "deno" in the past and now "bun"
if (typeof server.unref === 'function') {
Expand Down

0 comments on commit c065147

Please sign in to comment.