Skip to content

Instantly share code, notes, and snippets.

@mikeal
Created February 16, 2012 01:33
Show Gist options
  • Save mikeal/1840641 to your computer and use it in GitHub Desktop.
Save mikeal/1840641 to your computer and use it in GitHub Desktop.
get a new/clean port with node.js
var portrange = 45032
function getPort (cb) {
var port = portrange
portrange += 1
var server = net.createServer()
server.listen(port, function (err) {
server.once('close', function () {
cb(port)
})
server.close()
})
server.on('error', function (err) {
getPort(cb)
})
}
@matthewadams
Copy link

matthewadams commented Jan 3, 2020

@ronen & @jonathantneal, reraise:

import { createServer } from 'net'

function getPort (port = 80, maxPort = 65535) {
  if ((maxPort = parseInt(maxPort)) < (port = parseInt(port))) {
    return Promise.reject((() => {
      const e = new Error('EPORTSPEC')
      e.code = e.message
      return e
    })())
  }
  const server = createServer()
  return new Promise((resolve, reject) => server
    .once('error', error => error.code !== 'EADDRINUSE' || ++port > maxPort ? reject(error) : server.listen(port))
    .once('listening', () => server.close(() => resolve(port)))
    .listen(port)
  )
}

NB: edited to remove port range checks since server.listen has that check; only need to check that maxPort > port.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment