Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Be able to use a random port for the TCP server #12761

Merged
merged 2 commits into from
Nov 6, 2024

Conversation

PieterScheffers
Copy link
Contributor

@PieterScheffers PieterScheffers commented Nov 16, 2023

In the docs from Node net server:

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.

In the current code 0 is handled as a falsey value, which means the TCP server uses the TCP_DEFAULT_PORT value (3000) instead of letting the OS determine a random port.

Using a random free port is especially handy when running tests.

To get the port I am currently using the following function:

export const getAppTcpAddress = (app: INestMicroservice) => {
  const serverTcp = (app as NestMicroservice)?.['server']
  if (!(serverTcp instanceof ServerTCP)) return null

  const server = serverTcp?.['server']
  if (!(server instanceof Server)) return null

  return server.address()
}

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

@coveralls
Copy link

Pull Request Test Coverage Report for Build b4a45066-ea2a-4421-90c5-fe0060375bc8

  • 1 of 1 (100.0%) changed or added relevant line in 1 file are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 92.26%

Totals Coverage Status
Change from base Build 23ebebfc-1ad4-4b2b-8c07-2691151ef178: 0.0%
Covered Lines: 6687
Relevant Lines: 7248

💛 - Coveralls

@kamilmysliwiec kamilmysliwiec added this to the 11.0.0 milestone Nov 6, 2024
@kamilmysliwiec kamilmysliwiec changed the base branch from master to 11.0.0 November 6, 2024 11:47
@kamilmysliwiec kamilmysliwiec merged commit 0f38439 into nestjs:11.0.0 Nov 6, 2024
5 checks passed
@kamilmysliwiec kamilmysliwiec mentioned this pull request Nov 20, 2024
12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants