1
1
#!/usr/bin/env node
2
- import { existsSync , readFileSync } from 'node:fs'
2
+ import { existsSync , readFileSync , writeFileSync } from 'node:fs'
3
3
import { extname , join } from 'node:path'
4
4
import { parseArgs } from 'node:util'
5
5
@@ -16,6 +16,7 @@ import { Data } from './service.js'
16
16
17
17
function help ( ) {
18
18
console . log ( `Usage: json-server [options] <file>
19
+
19
20
Options:
20
21
-p, --port <port> Port (default: 3000)
21
22
-h, --host <host> Host (default: localhost)
@@ -114,6 +115,11 @@ if (!existsSync(file)) {
114
115
process . exit ( 1 )
115
116
}
116
117
118
+ // Handle empty string JSON file
119
+ if ( readFileSync ( file , 'utf-8' ) . trim ( ) === '' ) {
120
+ writeFileSync ( file , '{}' )
121
+ }
122
+
117
123
// Set up database
118
124
let adapter : Adapter < Data >
119
125
if ( extname ( file ) === '.json5' ) {
@@ -133,13 +139,19 @@ await db.read()
133
139
const app = createApp ( db , { logger : false , static : staticArr } )
134
140
135
141
function 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
+ }
136
149
console . log (
137
- [
138
- chalk . bold ( 'Endpoints:' ) ,
139
- ...Object . keys ( data ) . map (
150
+ Object . keys ( data )
151
+ . map (
140
152
( key ) => `${ chalk . gray ( `http://${ host } :${ port } /` ) } ${ chalk . blue ( key ) } ` ,
141
- ) ,
142
- ] . join ( '\n' ) ,
153
+ )
154
+ . join ( '\n' ) ,
143
155
)
144
156
}
145
157
0 commit comments