getProcessForPort.js 1.89 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

12
13
14
15
16
17
18
19
20
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)
21
22
    'ignore', //stderr
  ],
23
24
25
26
27
28
29
};

function isProcessAReactApp(processCommand) {
  return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand);
}

function getProcessIdOnPort(port) {
30
31
32
  return execSync('lsof -i:' + port + ' -P -t -sTCP:LISTEN', execOptions)
    .split('\n')[0]
    .trim();
33
34
35
36
37
38
39
}

function getPackageNameInDirectory(directory) {
  var packagePath = path.join(directory.trim(), 'package.json');

  try {
    return require(packagePath).name;
40
  } catch (e) {
41
42
43
44
45
    return null;
  }
}

function getProcessCommand(processId, processDirectory) {
46
47
48
49
  var command = execSync(
    'ps -o command -p ' + processId + ' | sed -n 2p',
    execOptions
  );
50
51
52

  if (isProcessAReactApp(command)) {
    const packageName = getPackageNameInDirectory(processDirectory);
53
    return packageName ? packageName + '\n' : command;
54
55
56
57
58
59
  } else {
    return command;
  }
}

function getDirectoryOfProcessById(processId) {
60
61
62
63
  return execSync(
    'lsof -p ' + processId + ' | awk \'$4=="cwd" {print $9}\'',
    execOptions
  ).trim();
64
65
66
67
68
69
70
71
}

function getProcessForPort(port) {
  try {
    var processId = getProcessIdOnPort(port);
    var directory = getDirectoryOfProcessById(processId);
    var command = getProcessCommand(processId, directory);
    return chalk.cyan(command) + chalk.blue('  in ') + chalk.cyan(directory);
72
  } catch (e) {
73
74
75
76
77
    return null;
  }
}

module.exports = getProcessForPort;