-
Notifications
You must be signed in to change notification settings - Fork 0
/
getProcessForPort.js
76 lines (63 loc) · 1.7 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
var color = require('colors-cli');
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)
.split('\n')[0]
.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
);
command = command.replace(/\n$/, '');
if (isProcessAReactApp(command)) {
const packageName = getPackageNameInDirectory(processDirectory);
return packageName ? packageName : command;
} else {
return command;
}
}
function getDirectoryOfProcessById(processId) {
return execSync(
'lsof -p ' + processId + ' | awk \'$4=="cwd" {print $9}\'',
execOptions
).trim();
}
function getProcessForPort(port) {
try {
var processId = getProcessIdOnPort(port);
var directory = getDirectoryOfProcessById(processId);
var command = getProcessCommand(processId, directory);
return (
color.cyan(command) +
color.grey(' (pid ' + processId + ')\n') +
color.blue(' in ') +
color.cyan(directory)
);
} catch (e) {
return null;
}
}
module.exports = getProcessForPort;