UNPKG

2.37 kBJavaScriptView Raw
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18'use strict'
19
20const net = require('net')
21
22/**
23 * Tests if a port is free.
24 * @param {number} port The port to test.
25 * @param {string=} opt_host The bound host to test the {@code port} against.
26 * Defaults to {@code INADDR_ANY}.
27 * @return {!Promise<boolean>} A promise that will resolve with whether the port
28 * is free.
29 */
30function isFree(port, opt_host) {
31 return new Promise((resolve, reject) => {
32 let server = net.createServer().on('error', function (e) {
33 if (e.code === 'EADDRINUSE' || e.code === 'EACCES') {
34 resolve(false)
35 } else {
36 reject(e)
37 }
38 })
39
40 server.listen(port, opt_host, function () {
41 server.close(() => resolve(true))
42 })
43 })
44}
45
46/**
47 * @param {string=} opt_host The bound host to test the {@code port} against.
48 * Defaults to {@code INADDR_ANY}.
49 * @return {!Promise<number>} A promise that will resolve to a free port. If a
50 * port cannot be found, the promise will be rejected.
51 */
52
53function findFreePort(opt_host) {
54 return new Promise((resolve, reject) => {
55 const server = net.createServer()
56 server.on('listening', function () {
57 resolve(server.address().port)
58 server.close()
59 })
60 server.on('error', (e) => {
61 if (e.code === 'EADDRINUSE' || e.code === 'EACCES') {
62 resolve('Unable to find a free port')
63 } else {
64 reject(e)
65 }
66 })
67 // By providing 0 we let the operative system find an arbitrary port
68 server.listen(0, opt_host)
69 })
70}
71
72// PUBLIC API
73
74exports.findFreePort = findFreePort
75exports.isFree = isFree