@@ -1076,14 +1076,18 @@ function getLocalIP() {
10761076 return preferred ? preferred . address : "localhost" ;
10771077}
10781078
1079- function findFreePort ( start ) {
1080- return new Promise ( ( resolve ) => {
1081- const srv = net . createServer ( ) ;
1082- srv . listen ( start , ( ) => {
1083- const port = srv . address ( ) . port ;
1084- srv . close ( ( ) => resolve ( port ) ) ;
1079+
1080+ function listenOnFreePort ( server , preferredPort ) {
1081+ return new Promise ( ( resolve , reject ) => {
1082+ server . listen ( preferredPort , ( ) => resolve ( server . address ( ) . port ) ) ;
1083+ server . on ( 'error' , ( err ) => {
1084+ if ( err . code === 'EADDRINUSE' ) {
1085+ server . removeAllListeners ( 'error' ) ;
1086+ listenOnFreePort ( server , preferredPort + 1 ) . then ( resolve ) . catch ( reject ) ;
1087+ } else {
1088+ reject ( err ) ;
1089+ }
10851090 } ) ;
1086- srv . on ( "error" , ( ) => resolve ( findFreePort ( start + 1 ) ) ) ;
10871091 } ) ;
10881092}
10891093
@@ -1093,18 +1097,19 @@ const localIP = getLocalIP();
10931097
10941098let PORT ;
10951099if ( process . env . INSTBYTE_BOOT === '1' ) {
1096- findFreePort ( PREFERRED ) . then ( p => {
1100+ listenOnFreePort ( server , PREFERRED ) . then ( p => {
10971101 PORT = p ;
1098- server . listen ( PORT , ( ) => {
1099- console . log ( "\nInstbyte running" ) ;
1100- console . log ( "Local: http://localhost:" + PORT ) ;
1101- console . log ( "Network: http://" + localIP + ":" + PORT ) ;
1102- if ( PORT !== PREFERRED ) {
1103- console . log ( `(port ${ PREFERRED } was busy, switched to ${ PORT } )` ) ;
1104- }
1105- console . log ( "" ) ;
1106- scanOrphans ( ) ;
1107- } ) ;
1102+ console . log ( "\nInstbyte running" ) ;
1103+ console . log ( "Local: http://localhost:" + PORT ) ;
1104+ console . log ( "Network: http://" + localIP + ":" + PORT ) ;
1105+ if ( PORT !== PREFERRED ) {
1106+ console . log ( `(port ${ PREFERRED } was busy, switched to ${ PORT } )` ) ;
1107+ }
1108+ console . log ( "" ) ;
1109+ scanOrphans ( ) ;
1110+ } ) . catch ( err => {
1111+ console . error ( "Failed to start server:" , err . message ) ;
1112+ process . exit ( 1 ) ;
11081113 } ) ;
11091114}
11101115
0 commit comments