aboutsummaryrefslogtreecommitdiff
path: root/node_modules/get-port/index.js
blob: fbd74e6e6ed2b9cb580070f1c1f0c6bfe2673d63 (plain)
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
'use strict';
const net = require('net');

const getPort = options => new Promise((resolve, reject) => {
	// For backwards compatibility with number-only input
	// TODO: Remove this in the next major version
	if (typeof options === 'number') {
		options = {
			port: options
		};
	}

	const server = net.createServer();

	server.unref();
	server.on('error', reject);

	server.listen(options, () => {
		const port = server.address().port;
		server.close(() => {
			resolve(port);
		});
	});
});

module.exports = options => options ?
	getPort(options).catch(() => getPort(0)) :
	getPort(0);