@@ -15,6 +15,8 @@ import { createApp } from './app.js'
1515import { Observer } from './observer.js'
1616import { Data } from './service.js'
1717
18+ let currentPort = 0 ;
19+
1820function help ( ) {
1921 console . log ( `Usage: json-server [options] <file>
2022
@@ -142,7 +144,7 @@ await db.read()
142144// Create app
143145const app = createApp ( db , { logger : false , static : staticArr } )
144146
145- function logRoutes ( data : Data ) {
147+ function logRoutes ( data : Data , port : number ) {
146148 console . log ( chalk . bold ( 'Endpoints:' ) )
147149 if ( Object . keys ( data ) . length === 0 ) {
148150 console . log (
@@ -166,25 +168,42 @@ function randomItem(items: string[]): string {
166168 return items . at ( index ) ?? ''
167169}
168170
169- app . listen ( port , ( ) => {
170- console . log (
171- [
172- chalk . bold ( `JSON Server started on PORT :${ port } ` ) ,
173- chalk . gray ( 'Press CTRL-C to stop' ) ,
174- chalk . gray ( `Watching ${ file } ...` ) ,
175- '' ,
176- chalk . magenta ( randomItem ( kaomojis ) ) ,
177- '' ,
178- chalk . bold ( 'Index:' ) ,
179- chalk . gray ( `http://localhost:${ port } /` ) ,
180- '' ,
181- chalk . bold ( 'Static files:' ) ,
182- chalk . gray ( 'Serving ./public directory if it exists' ) ,
183- '' ,
184- ] . join ( '\n' ) ,
185- )
186- logRoutes ( db . data )
187- } )
171+ function startServer ( port : number ) {
172+ const server = app . listen ( port ) ;
173+
174+ server . on ( 'listening' , ( ) => {
175+ currentPort = port ;
176+ {
177+ console . log (
178+ [
179+ chalk . bold ( `JSON Server started on PORT :${ port } ` ) ,
180+ chalk . gray ( 'Press CTRL-C to stop' ) ,
181+ chalk . gray ( `Watching ${ file } ...` ) ,
182+ '' ,
183+ chalk . magenta ( randomItem ( kaomojis ) ) ,
184+ '' ,
185+ chalk . bold ( 'Index:' ) ,
186+ chalk . gray ( `http://localhost:${ port } /` ) ,
187+ '' ,
188+ chalk . bold ( 'Static files:' ) ,
189+ chalk . gray ( 'Serving ./public directory if it exists' ) ,
190+ '' ,
191+ ] . join ( '\n' ) ,
192+ )
193+ logRoutes ( db . data , currentPort ) ;
194+ }
195+ } )
196+
197+ server . on ( 'error' , ( err : NodeJS . ErrnoException & { port ?: number } ) => {
198+ if ( err . code === 'EADDRINUSE' ) {
199+ startServer ( port + 1 ) ; // recursion
200+ } else {
201+ console . error ( 'Server error:' , err ) ;
202+ }
203+ } )
204+ }
205+
206+ startServer ( port ) ;
188207
189208// Watch file for changes
190209if ( process . env [ 'NODE_ENV' ] !== 'production' ) {
@@ -208,7 +227,7 @@ if (process.env['NODE_ENV'] !== 'production') {
208227 const nextEndpoints = JSON . stringify ( Object . keys ( data ) . sort ( ) )
209228 if ( prevEndpoints !== nextEndpoints ) {
210229 console . log ( )
211- logRoutes ( data )
230+ logRoutes ( data , currentPort )
212231 }
213232 }
214233 watch ( file ) . on ( 'change' , ( ) => {
0 commit comments