wait-port.js 745 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. const debug = require('debug')('wait-port');
  3. const detect = require('./detect-port');
  4. const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  5. async function waitPort(port, options = {}) {
  6. const { retryInterval = 1000, retries = Infinity } = options;
  7. let count = 1;
  8. async function loop() {
  9. debug('retries', retries, 'count', count);
  10. if (count > retries) {
  11. const err = new Error('retries exceeded');
  12. err.retries = retries;
  13. err.count = count;
  14. throw err;
  15. }
  16. count++;
  17. const freePort = await detect(port);
  18. if (freePort === port) {
  19. await sleep(retryInterval);
  20. return loop();
  21. }
  22. return true;
  23. }
  24. return await loop();
  25. }
  26. module.exports = waitPort;