Zep
Zep

Reputation: 38

Does not understand how Javascript work in this code (using Coffeescript, Commander in Node.js)

I have some trouble using Commander in Node.js: parseInt not working properly in my code:

commander = require 'commander'

#parseInt = (str) => parseInt str   #I tried to include this line but not work.

commander
  .option '-n, --connection [n]', 'number of connection', parseInt, 5000
  .option '-m, --message [n]', 'number of messages', parseInt, 5000
  .parse process.argv

console.log commander.connection 
console.log commander.message 

When I use option -n 10000 -m 10000, the console produce:

NaN
NaN

I also notice this code with class work:

commander = require 'commander'

class MyCommand
  parseOpt: =>
    commander
      .option '-n, --connection [n]', 'number of connection', @parseInt, 5000
      .option '-m, --message [n]', 'number of messages', @parseInt, 5000
      .parse process.argv
    (@connection, @message} = commander
  run: =>
    @parseOpt()
    console.log @connection 
    console.log @message        
  parseInt: (str) => parseInt str

new MyCommand().run()

Why my code does not work while the 'class' code work? How to make my code work without using class? Thanks~

Upvotes: 0

Views: 64

Answers (1)

metalim
metalim

Reputation: 1613

parseInt expects 2 arguments: string to parse, and base number (defaults to 10).

commander calls provided function with 2 arguments: string to parse, and it's default value. So in the end your parseInt tries to parse string '10000' in base 5000, which is invalid base.

Try this:

commander = require 'commander'

commander
  .option '-n, --connection [n]', 'number of connection', Number, 5000
  .option '-m, --message [n]', 'number of messages', Number, 5000
  .parse process.argv

console.log commander.connection
console.log commander.message

Also, the reason why your parseInt = (str) => parseInt str does not work, is that you're defining recursive function that just calls itself.

Upvotes: 1

Related Questions