findPort.js 990 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const pRetry = require('p-retry');
  3. const portfinder = require('portfinder');
  4. const defaultPort = require('./defaultPort');
  5. const defaultTo = require('./defaultTo');
  6. const tryParseInt = require('./tryParseInt');
  7. function runPortFinder() {
  8. return new Promise((resolve, reject) => {
  9. portfinder.basePort = defaultPort;
  10. portfinder.getPort((error, port) => {
  11. if (error) {
  12. return reject(error);
  13. }
  14. return resolve(port);
  15. });
  16. });
  17. }
  18. function findPort(port) {
  19. if (port) {
  20. return Promise.resolve(port);
  21. }
  22. // Try to find unused port and listen on it for 3 times,
  23. // if port is not specified in options.
  24. // Because NaN == null is false, defaultTo fails if parseInt returns NaN
  25. // so the tryParseInt function is introduced to handle NaN
  26. const defaultPortRetry = defaultTo(
  27. tryParseInt(process.env.DEFAULT_PORT_RETRY),
  28. 3
  29. );
  30. return pRetry(runPortFinder, { retries: defaultPortRetry });
  31. }
  32. module.exports = findPort;