diff --git a/bin/cmd.js b/bin/cmd.js index 1e393009..9d8869f3 100755 --- a/bin/cmd.js +++ b/bin/cmd.js @@ -14,6 +14,7 @@ var path = require('path') var prettyBytes = require('pretty-bytes') var WebTorrent = require('../') var zeroFill = require('zero-fill') +var grop = require('grop') process.title = 'WebTorrent' @@ -67,10 +68,7 @@ var argv = minimist(process.argv.slice(2), { 'subtitles', 'on-done', 'on-exit' - ], - default: { - port: 8000 - } + ] }) if (process.env.DEBUG || argv.stdout) { @@ -310,10 +308,18 @@ function runDownload (torrentId) { // Start http server server = torrent.createServer() - server.listen(argv.port, function () { - if (torrent.ready) onReady() - else torrent.once('ready', onReady) + + // Find available port + grop(function (availablePort) { + // if port is specified the use that + var port = argv.port || availablePort + + server.listen(port, function () { + if (torrent.ready) onReady() + else torrent.once('ready', onReady) + }) }) + server.once('connection', function () { serving = true }) @@ -366,8 +372,8 @@ function runDownload (torrentId) { function onSelection (index) { href = (argv.airplay || argv.chromecast || argv.xbmc) - ? 'http://' + networkAddress() + ':' + argv.port + '/' + index - : 'http://localhost:' + argv.port + '/' + index + ? 'http://' + networkAddress() + ':' + server.address().port + '/' + index + : 'http://localhost:' + server.address().port + '/' + index if (playerName) torrent.files[index].select() if (argv.stdout) torrent.files[index].createReadStream().pipe(process.stdout) diff --git a/package.json b/package.json index 25f4e3dd..cfa08ee5 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "end-of-stream": "^1.0.0", "executable": "^1.1.0", "fs-chunk-store": "^1.3.4", + "grop": "^0.1.0", "hat": "0.0.3", "immediate-chunk-store": "^1.0.7", "inherits": "^2.0.1",