Skip to content

Custom type example

Lloyd Brookes edited this page Jan 14, 2018 · 3 revisions

Demonstrates a custom type function returning a class instance.

const commandLineArgs = require('command-line-args')

class FileDetails {
  constructor (filename) {
    const fs = require('fs')
    this.filename = filename
    this.exists = fs.existsSync(filename)
  }
}

const optionDefinitions = [
  {
    name: 'file',
    multiple: true,
    defaultOption: true,
    type: filename => new FileDetails(filename)
  }
]

const options = commandLineArgs(optionDefinitions)

console.log(options)

Example output.

$ node example/type.js package.json nothing.js
{ file:
   [ FileDetails { filename: 'package.json', exists: true },
     FileDetails { filename: 'nothing.js', exists: false } ] }