getProcessForPort.js 1.97 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
  command = command.replace(/\n$/, '')

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

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

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

module.exports = getProcessForPort;