forked from sindresorhus/get-port
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
32 lines (28 loc) · 824 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'use strict';
const net = require('net');
const isAvailable = options => new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(options, () => {
const {port} = server.address();
server.close(() => {
resolve(port);
});
});
});
const getPort = (options = {}) => new Promise((resolve, reject) => {
if (typeof options.port === 'number') {
options.port = [options.port];
}
options.port.reduce((seq, port) => {
return seq.catch(() => {
return isAvailable(Object.assign({}, options, {port}))
.then(port => port)
.catch(Promise.reject.bind(Promise));
});
}, Promise.reject()).then(resolve).catch(reject);
});
module.exports = options => options ?
getPort(options).catch(() => getPort({port: 0})) :
getPort({port: 0});