├── index.js ├── package.json ├── readme.md └── test.js /index.js: -------------------------------------------------------------------------------- 1 | var net = require('net') 2 | 3 | function openport (start, end, cb) { 4 | if (!cb) { 5 | if (!end) { 6 | cb = start 7 | start = 2000 8 | end = 60000 9 | } else { 10 | cb = end 11 | end = 60000 12 | } 13 | } 14 | if (start >= end) return cb(new Error('out of ports :(')) 15 | 16 | var c = net.connect(start, function () { 17 | c.destroy() 18 | openport(start+1, end, cb) 19 | }) 20 | c.on('error', function () { 21 | cb(null, start) 22 | }) 23 | } 24 | 25 | module.exports = openport -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "getport", 3 | "version": "0.1.1", 4 | "description": "Find an open port to listen on.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node test.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/mikeal/getport" 12 | }, 13 | "keywords": [ 14 | "port", 15 | "open" 16 | ], 17 | "author": "Mikeal Rogers ", 18 | "license": "BSD", 19 | "bugs": { 20 | "url": "https://github.com/mikeal/getport/issues" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ### getport 2 | 3 | `npm install getport` 4 | 5 | Find an open port to listen on. 6 | 7 | #### `getport(function (e, port) {})` 8 | 9 | ```javascript 10 | var getport = require('getport') 11 | getport(function (e, p) { 12 | if (e) throw e 13 | server.listen(p) 14 | }) 15 | ``` 16 | 17 | *Note: getport uses a TCP client to check the ports and see if anyone has bound to them. If you do not have permission to bind to a port you may still get an error.* 18 | 19 | #### `getport(start, function (e, port) {})` 20 | 21 | ```javascript 22 | getport(5000, function (e, p) { 23 | if (e) throw e 24 | assert.equal(5000, p) 25 | }) 26 | ``` 27 | 28 | #### `getport(start, end, function (e, port) {})` 29 | 30 | ```javascript 31 | getport(6000, 5999, function (e, p) { 32 | assert.ok(e) 33 | }) 34 | ``` -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert') 2 | , getport = require('./') 3 | ; 4 | getport(5000, function (e, p) { 5 | if (e) throw e 6 | assert.equal(5000, p) 7 | getport(6000, 5999, function (e, p) { 8 | assert.ok(e) 9 | getport(function (e, p) { 10 | if (e) throw e 11 | assert.equal(p, 2000) 12 | console.log('all tests pass.') 13 | }) 14 | }) 15 | }) --------------------------------------------------------------------------------