11#!/usr/bin/env node
2- import { readFileSync } from 'node:fs'
2+ import { existsSync , readFileSync } from 'node:fs'
33import { extname , join } from 'node:path'
44import { parseArgs } from 'node:util'
55
@@ -41,7 +41,7 @@ const { values, positionals } = parseArgs({
4141} )
4242
4343if ( values . help || positionals . length === 0 ) {
44- console . log ( `Usage: json-server [options] [ file]
44+ console . log ( `Usage: json-server [options] < file>
4545Options:
4646 -p, --port <port> Port (default: 3000)
4747 -h, --host <host> Host (default: localhost)
@@ -59,10 +59,21 @@ if (values.version) {
5959}
6060
6161// App args and options
62- const file = positionals [ 0 ] ?? 'db.json '
62+ const file = positionals [ 0 ] ?? ''
6363const port = parseInt ( values . port ?? process . env [ 'PORT' ] ?? '3000' )
6464const host = values . host ?? process . env [ 'HOST' ] ?? 'localhost'
6565
66+ // Check file
67+ if ( file === '' ) {
68+ console . log ( 'No file specified' )
69+ process . exit ( 1 )
70+ }
71+
72+ if ( ! existsSync ( file ) ) {
73+ console . log ( `File ${ file } not found` )
74+ process . exit ( 1 )
75+ }
76+
6677// Set up database
6778let adapter : Adapter < Data >
6879if ( extname ( file ) === '.json5' ) {
@@ -95,8 +106,8 @@ if (process.env['NODE_ENV'] !== 'production') {
95106 observer . onWriteEnd = ( ) => {
96107 writing = false
97108 }
98- observer . onReadStart = ( ) => console . log ( `reloading ${ file } ...` )
99- observer . onReadEnd = ( ) => console . log ( 'reloaded ' )
109+ observer . onReadStart = ( ) => console . log ( `Reloading ${ file } ...` )
110+ observer . onReadEnd = ( ) => console . log ( 'Reloaded ' )
100111 watch ( file ) . on ( 'change' , ( ) => {
101112 // Do no reload if the file is being written to by the app
102113 if ( ! writing ) {
@@ -114,5 +125,5 @@ if (process.env['NODE_ENV'] !== 'production') {
114125
115126app . listen ( port , ( ) => {
116127 console . log ( `Started on :${ port } ` )
117- console . log ( routes ( db ) )
128+ console . log ( routes ( db ) . join ( '\n' ) )
118129} )
0 commit comments