You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
990 B

4 years ago
  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;