/
choosePort.ts
134 lines (123 loc) · 3.66 KB
/
choosePort.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* This feature was heavily inspired by create-react-app and
* uses many of the same utility functions to implement it.
*/
import {execSync} from 'child_process';
import detect from 'detect-port';
import isRoot from 'is-root';
import chalk from 'chalk';
import prompts from 'prompts';
const isInteractive = process.stdout.isTTY;
const execOptions: Record<string, unknown> = {
encoding: 'utf8',
stdio: [
'pipe', // stdin (default)
'pipe', // stdout (default)
'ignore', // stderr
],
};
// Clears console
function clearConsole(): void {
process.stdout.write(
process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H',
);
}
// Gets process id of what is on port
function getProcessIdOnPort(port: number): string {
return execSync(`lsof -i:${port} -P -t -sTCP:LISTEN`, execOptions)
.toString()
.split('\n')[0]
.trim();
}
// Gets process command
function getProcessCommand(processId: string): string {
const command: Buffer = execSync(
`ps -o command -p ${processId} | sed -n 2p`,
execOptions,
);
return command.toString().replace(/\n$/, '');
}
// Gets directory of a process from its process id
function getDirectoryOfProcessById(processId: string): string {
return execSync(
`lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`,
execOptions,
)
.toString()
.trim();
}
// Gets process on port
function getProcessForPort(port: number): string | null {
try {
const processId = getProcessIdOnPort(port);
const directory = getDirectoryOfProcessById(processId);
const command = getProcessCommand(processId);
return (
chalk.cyan(command) +
chalk.grey(` (pid ${processId})\n`) +
chalk.blue(' in ') +
chalk.cyan(directory)
);
} catch (e) {
return null;
}
}
/**
* Detects if program is running on port and prompts user
* to choose another if port is already being used
*/
export default async function choosePort(
host: string,
defaultPort: number,
): Promise<number | null> {
return detect({port: defaultPort, hostname: host}).then(
(port) =>
new Promise((resolve) => {
if (port === defaultPort) {
return resolve(port);
}
const message =
process.platform !== 'win32' && defaultPort < 1024 && !isRoot()
? `Admin permissions are required to run a server on a port below 1024.`
: `Something is already running on port ${defaultPort}.`;
if (isInteractive) {
clearConsole();
const existingProcess = getProcessForPort(defaultPort);
const question: prompts.PromptObject = {
type: 'confirm',
name: 'shouldChangePort',
message: `${chalk.yellow(
`${message}${
existingProcess ? ` Probably:\n ${existingProcess}` : ''
}`,
)}\n\nWould you like to run the app on another port instead?`,
initial: true,
};
prompts(question).then((answer) => {
if (answer.shouldChangePort === true) {
resolve(port);
} else {
resolve(null);
}
});
} else {
console.log(chalk.red(message));
resolve(null);
}
return null;
}),
(err) => {
throw new Error(
`${chalk.red(`Could not find an open port at ${chalk.bold(host)}.`)}\n${
`Network error message: "${err.message}".` || err
}\n`,
);
},
);
}