-
-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support array of preferred ports (#21)
- Loading branch information
1 parent
e9a39e0
commit f5c9753
Showing
3 changed files
with
74 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,38 @@ | ||
'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 isAvailable = options => new Promise((resolve, reject) => { | ||
const server = net.createServer(); | ||
|
||
server.unref(); | ||
server.on('error', reject); | ||
|
||
server.listen(options, () => { | ||
const port = server.address().port; | ||
const {port} = server.address(); | ||
server.close(() => { | ||
resolve(port); | ||
}); | ||
}); | ||
}); | ||
|
||
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}; | ||
} | ||
|
||
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(0)) : | ||
getPort(0); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters