Skip to content

Commit

Permalink
fix: use random port when port: 0 is set
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 27, 2023
1 parent cee453a commit 081ed99
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,18 @@ export async function getPort(config: GetPortInput = {}): Promise<PortNumber> {
config = { port: Number.parseInt(config + "") || 0 };
}

const _port = Number(config.port ?? process.env.PORT ?? 3000);

const options = {
name: "default",
random: false,
random: _port === 0,
ports: [],
portRange: [],
alternativePortRange: config.port ? [] : [3000, 3100],
host: undefined,
verbose: false,
...config,
port: config.port || Number.parseInt(process.env.PORT || "") || 3000,
port: _port,
} as GetPortOptions;

if (options.random) {
Expand Down
18 changes: 14 additions & 4 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,20 @@ describe("getPort (host)", () => {
});
});

describe("getPort (random)", () => {
test('getRandomPort', async () => {
describe("getPort: random", () => {
test("{ random: true }", async () => {
const port = await getPort({ random: true });
expect(typeof port).toBe("number");
expect(port).not.toBe(3000);
})
})
});

test("{ port: 0 }", async () => {
let port = await getPort({ port: 0 });
expect(typeof port).toBe("number");
expect(port).not.toBe(3000);

port = await getPort({ port: "0" as any });
expect(typeof port).toBe("number");
expect(port).not.toBe(3000);
});
});

0 comments on commit 081ed99

Please sign in to comment.