不明白Javascript在这个代码中是如何工作的(使用Coffeescript,Node.js中的Commander)



我在 Node.js 中使用 Commander 时遇到了一些问题:parseInt 在我的代码中无法正常工作:

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 

当我使用选项 -n 10000-m 10000 时,控制台产生:

NaN
NaN

我还注意到了这段带有类工作的代码:

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()

为什么我的代码不起作用,而"类"代码工作?如何在不使用类的情况下使我的代码工作?谢谢~

parseInt需要 2 个参数:要解析的字符串和基数(默认为10(。

commander调用提供的函数有 2 个参数:要解析的字符串,它是默认值。 因此,最终您的parseInt尝试解析 base 5000 中的字符串'10000',这是无效的 base。

试试这个:

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

此外,您的parseInt = (str) => parseInt str不起作用的原因是您正在定义仅调用自身的递归函数。

最新更新