|
5 | 5 | * Use of this source code is governed by an MIT-style license that can be
|
6 | 6 | * found in the LICENSE file at https://angular.io/license
|
7 | 7 | */
|
8 |
| - |
9 |
| -import { Observable } from 'rxjs'; |
10 | 8 | const net = require('net');
|
11 | 9 |
|
12 |
| -function getPort(options: any, callback: any, basePort = 49152) { |
13 |
| - const port = options.port || basePort; |
14 |
| - const server = net.createServer(); |
15 |
| - server.once('error', |
16 |
| - (err: any) => options.port === 0 |
17 |
| - ? getPort(options, callback, basePort+1) |
18 |
| - : callback(err, null) |
19 |
| - ); |
20 |
| - server.once('listening', () => { |
21 |
| - server.close(); |
22 |
| - callback(null, port); |
23 |
| - }); |
24 |
| - server.listen(port, options.host); |
25 |
| -} |
26 |
| - |
27 |
| -export function checkPort(port: number, host: string): Observable<number> { |
28 |
| - return new Observable(obs => { |
29 |
| - // tslint:disable:no-any |
30 |
| - getPort({ port, host }, (err: any, foundPort: number) => { |
31 |
| - if (err) { |
32 |
| - obs.error(err); |
33 |
| - } else if (port !== foundPort && port !== 0) { |
34 |
| - // If the port isn't available and we weren't looking for any port, throw error. |
35 |
| - obs.error(`Port ${port} is already in use. Use '--port' to specify a different port.`); |
36 |
| - } else { |
37 |
| - // Otherwise, our found port is good. |
38 |
| - obs.next(foundPort); |
39 |
| - obs.complete(); |
| 10 | +export function checkPort(port: number, host: string, basePort = 49152): Promise<number> { |
| 11 | + return new Promise<number>((resolve, reject) => { |
| 12 | + function _getPort(portNumber: number) { |
| 13 | + if (portNumber > 65535) { |
| 14 | + reject(new Error(`There is no port available.`)); |
40 | 15 | }
|
41 |
| - }); |
| 16 | + |
| 17 | + const server = net.createServer(); |
| 18 | + |
| 19 | + server.once('error', err => { |
| 20 | + if (port !== 0 && err.code === 'EADDRINUSE') { |
| 21 | + // If the port isn't available and we weren't looking for any port, throw error. |
| 22 | + reject(`Port ${port} is already in use. Use '--port' to specify a different port.`); |
| 23 | + } else if (port === 0) { |
| 24 | + reject(err); |
| 25 | + } |
| 26 | + |
| 27 | + _getPort(portNumber + 1); |
| 28 | + }) |
| 29 | + .once('listening', () => { |
| 30 | + server.close(); |
| 31 | + resolve(portNumber); |
| 32 | + }) |
| 33 | + .listen(portNumber, host); |
| 34 | + } |
| 35 | + |
| 36 | + _getPort(port || basePort); |
42 | 37 | });
|
43 | 38 | }
|
0 commit comments