-
-
Notifications
You must be signed in to change notification settings - Fork 26.8k
/
getProcessForPort.js
61 lines (48 loc) · 1.53 KB
/
getProcessForPort.js
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
var chalk = require('chalk');
var execSync = require('child_process').execSync;
var path = require('path');
var execOptions = {
encoding: 'utf8',
stdio: [
'pipe', // stdin (default)
'pipe', // stdout (default)
'ignore' //stderr
]
};
function isProcessAReactApp(processCommand) {
return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand);
}
function getProcessIdOnPort(port) {
return execSync('lsof -i:' + port + ' -P -t -sTCP:LISTEN', execOptions).trim();
}
function getPackageNameInDirectory(directory) {
var packagePath = path.join(directory.trim(), 'package.json');
try {
return require(packagePath).name;
} catch(e) {
return null;
}
}
function getProcessCommand(processId, processDirectory) {
var command = execSync('ps -o command -p ' + processId + ' | sed -n 2p', execOptions);
if (isProcessAReactApp(command)) {
const packageName = getPackageNameInDirectory(processDirectory);
return (packageName) ? packageName + '\n' : command;
} else {
return command;
}
}
function getDirectoryOfProcessById(processId) {
return execSync('lsof -p '+ processId + ' | grep cwd | awk \'{print $9}\'', execOptions).trim();
}
function getProcessForPort(port) {
try {
var processId = getProcessIdOnPort(port);
var directory = getDirectoryOfProcessById(processId);
var command = getProcessCommand(processId, directory);
return chalk.cyan(command) + chalk.blue(' in ') + chalk.cyan(directory);
} catch(e) {
return null;
}
}
module.exports = getProcessForPort;