getProcessForPort.js
1.91 KB
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
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
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)
.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" {for (i=9; i<=NF; i++) printf "%s ", $i}\'',
execOptions
).trim();
}
function getProcessForPort(port) {
try {
var processId = getProcessIdOnPort(port);
var directory = getDirectoryOfProcessById(processId);
var command = getProcessCommand(processId, directory);
return (
chalk.cyan(command) +
chalk.grey(' (pid ' + processId + ')\n') +
chalk.blue(' in ') +
chalk.cyan(directory)
);
} catch (e) {
return null;
}
}
module.exports = getProcessForPort;