我正在按照教程学习nodeJS。我们正在使用名为 app.js 的文件中的 Yargs 模块创建命令。到目前为止,一切都运行良好,直到教程要求我在 app.js 文件末尾更改一些代码。然后我开始遇到原始教程中没有的意外错误。
当 app.js 有以下行时,代码按预期工作:console.log(yargs.argv)
但是本教程要求我们将那行替换为:yargs.parse()。
控制台错误:
YError: Not enough arguments provided. Expected 1 but received 0.
at module.exports (C:\Users\officedepot\node_modules\yargs\lib\argsert.js:25
:13)
at Object.Yargs.self.parse (C:\Users\officedepot\node_modules\yargs\yargs.js
:510:5)
at Object.<anonymous> (C:\Users\officedepot\Desktop\nodedemo\nodeapp\command
s.js:56:7)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
C:\Users\officedepot\node_modules\yargs-parser\index.js:756
return parse(args.slice(), opts)
^
TypeError: Cannot read property 'slice' of undefined
at Function.Parser.detailed (C:\Users\officedepot\node_modules\yargs-parser\
index.js:756:21)
at Object.Yargs.self._parseArgs (C:\Users\officedepot\node_modules\yargs\yar
gs.js:941:27)
at Object.Yargs.self.parse (C:\Users\officedepot\node_modules\yargs\yargs.js
:533:23)
at Object.<anonymous> (C:\Users\officedepot\Desktop\nodedemo\nodeapp\command
s.js:56:7)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
APP.js
const yargs = require('yargs');
yargs.command({
command: 'add',
describe: 'add a new note',
builder: {
title: {
describe: 'Note title',
demandOption: true,
type: 'string'
}
},
handler: function(argv){
console.log('Title: ' + argv.title )
}
})
//console.log(yargs.argv); //this worked as predicted
yargs.parse() //this is the new line, which introduced the error shown.
这是我在节点 CMD 中运行的内容:
node app.js add --title="My Title"
我期待“标题:我的标题”。但是却收到了一个错误。