Skip to content

Commit

Permalink
Try a different port when given port is already in use. Close #29
Browse files Browse the repository at this point in the history
  • Loading branch information
amio committed Jul 2, 2016
1 parent d1ffa75 commit c25ec48
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions bin/serve
Expand Up @@ -136,7 +136,6 @@ if (program.exec) {
server.use(serveStatic(path, { hidden: program.hidden }));

// directory serving

if (program.dirs) {
server.use(serveIndex(path, {
hidden: program.hidden
Expand Down Expand Up @@ -221,12 +220,26 @@ if (program.https) {

}

// start the server
server.listen(program.port, function () {
console.log('\033[90mserving \033[36m%s\033[90m on port \033[96m%d\033[0m', path, program.port);

// open the browser window to this server
if (program.open) {
open('http://127.0.0.1' + (~~program.port > 0 && ~~program.port < 65536 ? ':' + ~~program.port : ''));
function onError (err) {
switch (err.code) {
case 'EADDRINUSE':
console.error('\033[33mWARN:\033[90m Port \033[33m%d\033[90m is already in use.', err.port);
launch(err.port + 1);
break;
default:
throw err;
}
});
}

function launch (port) {
return server.listen(port, function () {
// Successful message
console.log('\033[90mServing \033[36m%s\033[90m on port \033[96m%d\033[0m', path, port);

// open the browser window to this server
program.open && open('http://127.0.0.1:' + port);
}).on('error', onError);
}

// start the server
launch(program.port)

0 comments on commit c25ec48

Please sign in to comment.