Skip to content

Commit 99193da

Browse files
committed
feat: handle empty json file and improve output
1 parent af73a69 commit 99193da

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/bin.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env node
2-
import { existsSync, readFileSync } from 'node:fs'
2+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
33
import { extname, join } from 'node:path'
44
import { parseArgs } from 'node:util'
55

@@ -16,6 +16,7 @@ import { Data } from './service.js'
1616

1717
function help() {
1818
console.log(`Usage: json-server [options] <file>
19+
1920
Options:
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
118124
let adapter: Adapter<Data>
119125
if (extname(file) === '.json5') {
@@ -133,13 +139,19 @@ await db.read()
133139
const app = createApp(db, { logger: false, static: staticArr })
134140

135141
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+
}
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

Comments
 (0)