rsnext/packages/next/server/lib/utils.ts
Will Binns-Smith 643447ed03
Allow port 0 in next dev and next start (#40118)
This addresses a bug where invoking `next dev` or `next start` with `--port 0` would fall back to the default port of 3000 instead of binding to port 0 (which typically results in the operating system assigning a free port).

I couldn't find a straightforward way of adding a test for next-start. It looks like we could add a similar test as for dev, but would need to generate a built project to serve. 

Manual test plan for `next start`:
```
$ ./packages/next/dist/bin/next start --port 0
ready - started server on 0.0.0.0:53508, url: http://localhost:53508
```

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Wyatt Johnson <accounts+github@wyattjoh.ca>
2022-08-31 17:13:39 -05:00

29 lines
711 B
TypeScript

import type arg from 'next/dist/compiled/arg/index.js'
export function printAndExit(message: string, code = 1) {
if (code === 0) {
console.log(message)
} else {
console.error(message)
}
process.exit(code)
}
export function getNodeOptionsWithoutInspect() {
const NODE_INSPECT_RE = /--inspect(-brk)?(=\S+)?( |$)/
return (process.env.NODE_OPTIONS || '').replace(NODE_INSPECT_RE, '')
}
export function getPort(args: arg.Result<arg.Spec>): number {
if (typeof args['--port'] === 'number') {
return args['--port']
}
const parsed = process.env.PORT && parseInt(process.env.PORT, 10)
if (typeof parsed === 'number' && !Number.isNaN(parsed)) {
return parsed
}
return 3000
}