getProcessForPort.js 2.0 KB

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