UNPKG

1.92 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8'use strict';
9
10var chalk = require('chalk');
11var execSync = require('child_process').execSync;
12var path = require('path');
13
14var execOptions = {
15 encoding: 'utf8',
16 stdio: [
17 'pipe', // stdin (default)
18 'pipe', // stdout (default)
19 'ignore', //stderr
20 ],
21};
22
23function isProcessAReactApp(processCommand) {
24 return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand);
25}
26
27function getProcessIdOnPort(port) {
28 return execSync('lsof -i:' + port + ' -P -t -sTCP:LISTEN', execOptions)
29 .split('\n')[0]
30 .trim();
31}
32
33function 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
43function 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
59function getDirectoryOfProcessById(processId) {
60 return execSync(
61 'lsof -p ' + processId + ' | awk \'$4=="cwd" {print $9}\'',
62 execOptions
63 ).trim();
64}
65
66function 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
82module.exports = getProcessForPort;