bin.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #! /usr/bin/env node
  2. 'use strict';
  3. const path = require('path');
  4. const cfork = require('cfork');
  5. const InterceptorProxy = require('../');
  6. const packInfo = require('../package');
  7. const argv = process.argv;
  8. const DEFAULT_PROXY_PORT = 9229;
  9. const DEFAULT_DEBUG_PORT = 5858;
  10. // show help
  11. if (argv.includes('--help') || argv.includes('-h')) {
  12. return console.log(
  13. '\n' +
  14. 'Usage: inspector-proxy [options] [script.js]\n\n' +
  15. 'Options:\n' +
  16. ' -h, --help help \n' +
  17. ' -v, --version show version \n' +
  18. ' --proxy=port proxy port(default: ' + DEFAULT_PROXY_PORT + ') \n' +
  19. ' --debug=port node debug port(default: ' + DEFAULT_DEBUG_PORT + ') \n' +
  20. ' --silent=silent cfork silent(default: false) \n' +
  21. ' --refork=refork cfork refork(default: true) \n' +
  22. ' --file=file cfork exec file \n'
  23. );
  24. } else if (argv.includes('--version') || argv.includes('-v')) {
  25. return console.log(packInfo.version);
  26. }
  27. const proxyPort = getArg('--proxy') || DEFAULT_PROXY_PORT;
  28. const debugPort = getArg('--debug') || DEFAULT_DEBUG_PORT;
  29. const silent = getArg('--silent') === 'true';
  30. const refork = getArg('--refork') !== 'false';
  31. let jsFile = getArg('--file') || argv[argv.length - 1];
  32. const proxy = new InterceptorProxy({ port: proxyPort, silent });
  33. // don't run cfork while missing js file
  34. if (path.extname(jsFile) !== '.js') {
  35. return proxy.start({ proxyPort, debugPort })
  36. .then(() => {
  37. console.log(`\nproxy url: ${proxy.url}\n`);
  38. });
  39. }
  40. if (!path.isAbsolute(jsFile)) {
  41. jsFile = path.resolve(process.cwd(), jsFile);
  42. }
  43. // prevent cfork print epipe error
  44. /* istanbul ignore next */
  45. process.on('uncaughtException', err => {
  46. if (err.code !== 'EPIPE') {
  47. console.error(err);
  48. }
  49. });
  50. // hack to make cfork start with debugPort
  51. process.debugPort = debugPort - 1;
  52. // fork js
  53. cfork({
  54. exec: jsFile,
  55. execArgv: [ '--inspect' ],
  56. silent,
  57. count: 1,
  58. refork,
  59. }).on('fork', worker => {
  60. let port = debugPort;
  61. worker.process.spawnargs.find(arg => {
  62. let matches;
  63. if (arg.startsWith('--inspect') && (matches = arg.match(/\d+/))) {
  64. port = matches[0];
  65. return true;
  66. }
  67. return false;
  68. });
  69. proxy.start({ proxyPort, debugPort: port })
  70. .then(() => {
  71. console.log(`\nproxy url: ${proxy.url}\n`);
  72. });
  73. });
  74. function getArg(arg) {
  75. const key = `${arg}=`;
  76. const result = argv.find(item => item.startsWith(key));
  77. if (result) {
  78. return result.substring(key.length);
  79. }
  80. }