-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathcheck-port.ts
54 lines (46 loc) · 1.37 KB
/
check-port.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { prompt } from 'inquirer';
import * as net from 'net';
import { isTTY } from './tty';
function createInUseError(port: number): Error {
return new Error(`Port ${port} is already in use. Use '--port' to specify a different port.`);
}
export async function checkPort(port: number, host: string): Promise<number> {
if (port === 0) {
return 0;
}
return new Promise<number>((resolve, reject) => {
const server = net.createServer();
server
.once('error', (err: NodeJS.ErrnoException) => {
if (err.code !== 'EADDRINUSE') {
reject(err);
return;
}
if (!isTTY) {
reject(createInUseError(port));
return;
}
prompt({
type: 'confirm',
name: 'useDifferent',
message: `Port ${port} is already in use.\nWould you like to use a different port?`,
default: true,
}).then(
(answers) => answers.useDifferent ? resolve(0) : reject(createInUseError(port)),
() => reject(createInUseError(port)),
);
})
.once('listening', () => {
server.close();
resolve(port);
})
.listen(port, host);
});
}