11#!/usr/bin/env node
2- import { existsSync , readFileSync } from 'node:fs'
2+ import { existsSync , readFileSync , writeFileSync } from 'node:fs'
33import { extname , join } from 'node:path'
44import { parseArgs } from 'node:util'
55
@@ -16,6 +16,7 @@ import { Data } from './service.js'
1616
1717function help ( ) {
1818 console . log ( `Usage: json-server [options] <file>
19+
1920Options:
2021 -p, --port <port> Port (default: 3000)
2122 -h, --host <host> Host (default: localhost)
@@ -114,6 +115,11 @@ if (!existsSync(file)) {
114115 process . exit ( 1 )
115116}
116117
118+ // Handle empty string JSON file
119+ if ( readFileSync ( file , 'utf-8' ) . trim ( ) === '' ) {
120+ writeFileSync ( file , '{}' )
121+ }
122+
117123// Set up database
118124let adapter : Adapter < Data >
119125if ( extname ( file ) === '.json5' ) {
@@ -133,13 +139,19 @@ await db.read()
133139const app = createApp ( db , { logger : false , static : staticArr } )
134140
135141function logRoutes ( data : Data ) {
142+ console . log ( chalk . bold ( 'Endpoints:' ) )
143+ if ( Object . keys ( data ) . length === 0 ) {
144+ console . log (
145+ chalk . gray ( `No endpoints found, try adding some data to ${ file } ` ) ,
146+ )
147+ return
148+ }
136149 console . log (
137- [
138- chalk . bold ( 'Endpoints:' ) ,
139- ...Object . keys ( data ) . map (
150+ Object . keys ( data )
151+ . map (
140152 ( key ) => `${ chalk . gray ( `http://${ host } :${ port } /` ) } ${ chalk . blue ( key ) } ` ,
141- ) ,
142- ] . join ( '\n' ) ,
153+ )
154+ . join ( '\n' ) ,
143155 )
144156}
145157
0 commit comments