getProcessForPort.js 1.9 KB
Newer Older
1
2
3
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
Sophie Alpert's avatar
Sophie Alpert committed
4
5
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
6
7
8
9
 */

'use strict';

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

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

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

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

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

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

49
  command = command.replace(/\n$/, '');
50

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

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

function getProcessForPort(port) {
  try {
    var processId = getProcessIdOnPort(port);
    var directory = getDirectoryOfProcessById(processId);
    var command = getProcessCommand(processId, directory);
71
72
73
74
75
76
    return (
      chalk.cyan(command) +
      chalk.grey(' (pid ' + processId + ')\n') +
      chalk.blue('  in ') +
      chalk.cyan(directory)
    );
77
  } catch (e) {
78
79
80
81
82
    return null;
  }
}

module.exports = getProcessForPort;