1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | 'use strict';
|
9 |
|
10 | var chalk = require('chalk');
|
11 | var execSync = require('child_process').execSync;
|
12 | var path = require('path');
|
13 |
|
14 | var execOptions = {
|
15 | encoding: 'utf8',
|
16 | stdio: [
|
17 | 'pipe',
|
18 | 'pipe',
|
19 | 'ignore',
|
20 | ],
|
21 | };
|
22 |
|
23 | function isProcessAReactApp(processCommand) {
|
24 | return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand);
|
25 | }
|
26 |
|
27 | function getProcessIdOnPort(port) {
|
28 | return execSync('lsof -i:' + port + ' -P -t -sTCP:LISTEN', execOptions)
|
29 | .split('\n')[0]
|
30 | .trim();
|
31 | }
|
32 |
|
33 | function getPackageNameInDirectory(directory) {
|
34 | var packagePath = path.join(directory.trim(), 'package.json');
|
35 |
|
36 | try {
|
37 | return require(packagePath).name;
|
38 | } catch (e) {
|
39 | return null;
|
40 | }
|
41 | }
|
42 |
|
43 | function getProcessCommand(processId, processDirectory) {
|
44 | var command = execSync(
|
45 | 'ps -o command -p ' + processId + ' | sed -n 2p',
|
46 | execOptions
|
47 | );
|
48 |
|
49 | command = command.replace(/\n$/, '');
|
50 |
|
51 | if (isProcessAReactApp(command)) {
|
52 | const packageName = getPackageNameInDirectory(processDirectory);
|
53 | return packageName ? packageName : command;
|
54 | } else {
|
55 | return command;
|
56 | }
|
57 | }
|
58 |
|
59 | function getDirectoryOfProcessById(processId) {
|
60 | return execSync(
|
61 | 'lsof -p ' + processId + ' | awk \'$4=="cwd" {print $9}\'',
|
62 | execOptions
|
63 | ).trim();
|
64 | }
|
65 |
|
66 | function getProcessForPort(port) {
|
67 | try {
|
68 | var processId = getProcessIdOnPort(port);
|
69 | var directory = getDirectoryOfProcessById(processId);
|
70 | var command = getProcessCommand(processId, directory);
|
71 | return (
|
72 | chalk.cyan(command) +
|
73 | chalk.grey(' (pid ' + processId + ')\n') +
|
74 | chalk.blue(' in ') +
|
75 | chalk.cyan(directory)
|
76 | );
|
77 | } catch (e) {
|
78 | return null;
|
79 | }
|
80 | }
|
81 |
|
82 | module.exports = getProcessForPort;
|