Skip to content

Commit

Permalink
rework argv parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
grische committed Jul 26, 2024
1 parent 2d6ed4e commit b490b8c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 10 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,27 @@ Things to note:

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

### Usage

- Read JSON file:

```sh
node json-to-go.js sample.json
```

- Read JSON file from stdin:

```sh
node json-to-go.js < sample.json
cat sample.json | node json-to-go.js
```

- Read large JSON file from stdin:

```sh
node json-to-go.js --big < sample.json
cat sample.json | node json-to-go.js --big
```

### Credits

Expand Down
46 changes: 36 additions & 10 deletions json-to-go.js
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,35 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty

if (typeof module != 'undefined') {
if (!module.parent) {
if (process.argv.length > 2 && process.argv[2] === '-big') {
let bigstdin = false
let filename = null

process.argv.forEach((val, index) => {
if (index < 2)
return

if (!val.startsWith('-')) {
filename = val
return
}

const argument = val.replace(/-/g, '')
if (argument === "big")
bigstdin = true
else {
console.error(`Unexpected argument ${val} received`)
process.exit(1)
}
})

if (filename) {
const fs = require('fs');
const json = fs.readFileSync(filename, 'utf8');
process.stdout.write(jsonToGo(json).go)
return
}

if (bigstdin) {
bufs = []
process.stdin.on('data', function(buf) {
bufs.push(buf)
Expand All @@ -504,16 +532,14 @@ if (typeof module != 'undefined') {
const json = Buffer.concat(bufs).toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
} else if (process.argv.length === 3) {
const fs = require('fs');
const json = fs.readFileSync(process.argv[2], 'utf8');
process.stdout.write(jsonToGo(json).go)
} else {
process.stdin.on('data', function(buf) {
const json = buf.toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
return
}

// read from stdin
process.stdin.on('data', function(buf) {
const json = buf.toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
} else {
module.exports = jsonToGo
}
Expand Down

0 comments on commit b490b8c

Please sign in to comment.