detect-port 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env node
  2. 'use strict';
  3. const pkg = require('../package');
  4. const args = process.argv.slice(2);
  5. const arg_0 = args[0];
  6. if (!!~['-v', '--version'].indexOf(arg_0)) {
  7. console.log(pkg.version);
  8. process.exit(0);
  9. }
  10. const port = parseInt(arg_0, 10);
  11. const main = require('..');
  12. if (!arg_0) {
  13. const random = Math.floor(9000 + Math.random() * (65535 - 9000));
  14. main(random, (err, port) => {
  15. if (err) {
  16. console.log(`get available port failed with ${err}`);
  17. }
  18. console.log(`get available port ${port} randomly`);
  19. });
  20. } else if (isNaN(port)) {
  21. console.log();
  22. console.log(` \u001b[37m${pkg.description}\u001b[0m`);
  23. console.log();
  24. console.log(' Usage:');
  25. console.log();
  26. console.log(` ${pkg.name} [port]`);
  27. console.log();
  28. console.log(' Options:');
  29. console.log();
  30. console.log(' -v, --version show version and exit');
  31. console.log(' -h, --help output usage information');
  32. console.log();
  33. console.log(' Further help:');
  34. console.log();
  35. console.log(` ${pkg.homepage}`);
  36. console.log();
  37. } else {
  38. main(port, (err, _port) => {
  39. if (err) {
  40. console.log(`get available port failed with ${err}`);
  41. }
  42. if (port !== _port) {
  43. console.log(`port ${port} was occupied`);
  44. }
  45. console.log(`get available port ${_port}`);
  46. });
  47. }