forked from sindresorhus/get-port
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (48 loc) · 1.32 KB
/
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'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 => {
options = Object.assign({}, options);
if (typeof options.port === 'number') {
options.port = [options.port];
}
return (options.port || []).reduce(
(seq, port) => seq.catch(
() => isAvailable(Object.assign({}, options, {port}))
),
Promise.reject()
);
};
module.exports = options => options ?
getPort(options).catch(() => getPort(Object.assign(options, {port: 0}))) :
getPort({port: 0});
module.exports.makeRange = (from, to) => {
if (!Number.isInteger(from) || !Number.isInteger(to)) {
throw new TypeError('`from` and `to` must ne integer numbers');
}
if (from < 1025 || from > 65535) {
throw new RangeError('`from` must be between 1025 and 65535');
}
if (to < 1025 || to > 65536) {
throw new RangeError('`to` must be between 1025 and 65536');
}
if (from >= to) {
throw new RangeError('`to` must be greater than `from`');
}
const ports = [];
for (let port = from; port < to; port++) {
ports.push(port);
}
return ports;
};
module.exports.default = module.exports;