UNPKG

1.96 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 ' +
62 processId +
63 ' | awk \'$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}\'',
64 execOptions
65 ).trim();
66}
67
68function getProcessForPort(port) {
69 try {
70 var processId = getProcessIdOnPort(port);
71 var directory = getDirectoryOfProcessById(processId);
72 var command = getProcessCommand(processId, directory);
73 return (
74 chalk.cyan(command) +
75 chalk.grey(' (pid ' + processId + ')\n') +
76 chalk.blue(' in ') +
77 chalk.cyan(directory)
78 );
79 } catch (e) {
80 return null;
81 }
82}
83
84module.exports = getProcessForPort;