Skip to content

Commit b490b8c

Browse files
committed
rework argv parsing
1 parent 2d6ed4e commit b490b8c

File tree

2 files changed

+57
-10
lines changed

2 files changed

+57
-10
lines changed

README.md

+21
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,27 @@ Things to note:
1212

1313
Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.
1414

15+
### Usage
16+
17+
- Read JSON file:
18+
19+
```sh
20+
node json-to-go.js sample.json
21+
```
22+
23+
- Read JSON file from stdin:
24+
25+
```sh
26+
node json-to-go.js < sample.json
27+
cat sample.json | node json-to-go.js
28+
```
29+
30+
- Read large JSON file from stdin:
31+
32+
```sh
33+
node json-to-go.js --big < sample.json
34+
cat sample.json | node json-to-go.js --big
35+
```
1536

1637
### Credits
1738

json-to-go.js

+36-10
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,35 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
495495

496496
if (typeof module != 'undefined') {
497497
if (!module.parent) {
498-
if (process.argv.length > 2 && process.argv[2] === '-big') {
498+
let bigstdin = false
499+
let filename = null
500+
501+
process.argv.forEach((val, index) => {
502+
if (index < 2)
503+
return
504+
505+
if (!val.startsWith('-')) {
506+
filename = val
507+
return
508+
}
509+
510+
const argument = val.replace(/-/g, '')
511+
if (argument === "big")
512+
bigstdin = true
513+
else {
514+
console.error(`Unexpected argument ${val} received`)
515+
process.exit(1)
516+
}
517+
})
518+
519+
if (filename) {
520+
const fs = require('fs');
521+
const json = fs.readFileSync(filename, 'utf8');
522+
process.stdout.write(jsonToGo(json).go)
523+
return
524+
}
525+
526+
if (bigstdin) {
499527
bufs = []
500528
process.stdin.on('data', function(buf) {
501529
bufs.push(buf)
@@ -504,16 +532,14 @@ if (typeof module != 'undefined') {
504532
const json = Buffer.concat(bufs).toString('utf8')
505533
process.stdout.write(jsonToGo(json).go)
506534
})
507-
} else if (process.argv.length === 3) {
508-
const fs = require('fs');
509-
const json = fs.readFileSync(process.argv[2], 'utf8');
510-
process.stdout.write(jsonToGo(json).go)
511-
} else {
512-
process.stdin.on('data', function(buf) {
513-
const json = buf.toString('utf8')
514-
process.stdout.write(jsonToGo(json).go)
515-
})
535+
return
516536
}
537+
538+
// read from stdin
539+
process.stdin.on('data', function(buf) {
540+
const json = buf.toString('utf8')
541+
process.stdout.write(jsonToGo(json).go)
542+
})
517543
} else {
518544
module.exports = jsonToGo
519545
}

0 commit comments

Comments
 (0)