Commander.js: option string is always Undefined

Created on 12 Feb 2019  路  3Comments  路  Source: tj/commander.js

#!/usr/bin/env node

const program = require('commander');

program
  .command('verify <hash>')
  .option('-r, --root <root>', 'Root of the channel')
  .action(function (hash) {
    // console.log('remove ' + dir )
    console.log(hash, program.root)
  })
program.parse(process.argv)

Command line :

$ testit verify hashhh -r rootttt
hashhh undefined

it is not possible to get the passed string via options!
version 2.19.0

Most helpful comment

very bad, the documentation is outdated, thousands of people will go crazy debugging this issue - just a time waste

All 3 comments

You should be able to receive provided option as second argument of callback passed to Commander.action, e.g.:

const program = require('commander');

program
  .command('verify <hash>')
  .option('-r, --root <root>', 'Root of the channel')
  .action(function (hash, options) {
    // console.log('remove ' + dir )
    console.log(options.root);
    console.log(hash);
  })

program.parse(process.argv)

See also corresponding test: https://github.com/tj/commander.js/blob/3b8e519f963f7a2cb66adb671f05c56cd68af6da/test/test.options.commands.js#L36

very bad, the documentation is outdated, thousands of people will go crazy debugging this issue - just a time waste

Thanks for taking the time to provide a customised example in your reply @vanesyan

There is actually an example of this in the README @mtrabelsi, down the bottom:
https://github.com/tj/commander.js#examples

.action(function(cmd, options){
    console.log('exec "%s" using %s mode', cmd, options.exec_mode);
Was this page helpful?
0 / 5 - 0 ratings