UNPKG

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