Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created August 27, 2018 18:35
Show Gist options
  • Save hawkeye64/0f86c3469ab44a9bf6a0a676e6ea81ab to your computer and use it in GitHub Desktop.
Save hawkeye64/0f86c3469ab44a9bf6a0a676e6ea81ab to your computer and use it in GitHub Desktop.
command-line-args Example
const fs = require('fs')
const path = require('path')
const commandLineArgs = require('command-line-args')
/**
* Returns true if the passed in object is empty
* @param {Object} obj
*/
const isEmptyObject = (obj) => {
return JSON.stringify(obj) === JSON.stringify({})
}
const optionDefinitions = [
{ name: 'image', alias: 'i', type: String },
{ name: 'confidence', alias: 'c', type: Number },
{ name: 'filter', alias: 'f', type: String },
{ name: 'quick', alias: 'q' },
{ name: 'version', alias: 'v' },
{ name: 'help', alias: 'h' }
]
let options
try {
options = commandLineArgs(optionDefinitions)
}
catch(e) {
console.error()
console.error('classify:', e.name, e.optionName)
console.log(usage)
process.exit(1)
}
// check for help
if (isEmptyObject(options) || 'help' in options) {
console.log(usage)
process.exit(1)
}
// check for version
if ('version' in options) {
let pkg = require('./package.json')
console.log(pkg.version)
process.exit(1)
}
let imagePath
// check for path
if ('image' in options) {
imagePath = options.image
}
if (!imagePath) {
console.error('"--image imagePath" is required.')
process.exit(1)
}
if (!fs.existsSync(imagePath)) {
console.log(`exiting: could not find image: ${imagePath}`)
process.exit(2)
}
let confidence = 50 // default
if ('confidence' in options) {
confidence = options.confidence
}
// validate confidence
if (confidence < 0) {
console.error(`Negative numbers are not valid for 'confidence'.`)
process.exit(1)
}
if (confidence > 100) {
console.error(`A value greater than 100 is not valid for 'confidence'.`)
process.exit(1)
}
confidence = confidence / 100.0
let filterItems = []
if ('filter' in options) {
const filterFile = options.filter
// verify file exist
if (!fs.existsSync(filterFile)) {
console.log(`exiting: could not find filter file: ${filterFile}`)
process.exit(2)
}
filterItems = fs.readFileSync(filterFile).toString().split('\n')
}
// get quick option, if available - default to slow
let quick = false
if ('quick' in options) {
quick = true
}
// get data file based on model and quick options
let dataFile
if (model === 'coco') {
if (quick) {
dataFile = 'coco300'
}
else {
dataFile = 'coco512'
}
}
else if (model === 'inception') {
dataFile = 'inception224'
}
if (!dataFile) {
console.error(`'${model}' is not valid model.`)
process.exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment