Ger*_*ica 5 node.js node-commander
我把头靠在墙上,试图让节点的commander模块按照我想要的方式解析参数。
我希望将文件列表上传到命名数据库。有一个默认的数据库名称,因此用户不需要包含数据库参数。
我希望此命令按以下方式工作:
>>> ./upload.js --db ReallyCoolDB /files/uploadMe1.txt /files/uploadMe2.txt
(uploads "uploadMe1.txt" and "uploadMe2.txt" to database "ReallyCoolDB")
>>> ./upload.js /files/uploadMe1.txt /files/uploadMe2.txt
(uploads "uploadMe1.txt" and "uploadMe2.txt" to the default database)
>>> ./upload.js --db ReallyCoolDB
(returns an error; no files provided)
Run Code Online (Sandbox Code Playgroud)
我该如何实现commander?我已经尝试了很多东西,目前我坚持使用这个不起作用的代码:
// upload.js:
#!/usr/bin/env node
var program = require('commander');
program
.version('0.1.0')
.description('Upload files to a database')
.command('<path1> [morePaths...]')
.option('-d, --db [dbName]', 'Optional name of db', null)
.action(function(path1, morePaths) {
// At this point I simply want:
// 1) a String "dbName" var
// 2) an Array "paths" containing all the paths the user provided
var dbName = program.db || getDefaultDBName();
var paths = [ path1 ].concat(morePaths || []);
console.log(dbName, paths);
// ... do the upload ...
})
.parse(process.argv);
Run Code Online (Sandbox Code Playgroud)
当我尝试运行时./upload.js,我没有输出!
如何使用 Commander 接受单个可选参数和非空字符串列表?
编辑:感谢 Rob Raisch 的回答,我已经解决了我的问题!解决方案是使用usage而不是action,在program命令之后(而不是在action函数内)完成所有工作,使用program.db和program.args,并手动确保program.args非空:
var program = require('commander');
program
.version('0.1.0')
.description('Upload files to a database')
.usage('[options] <path1> [morePaths ...]') // This improves "--help" output
.option('-d, --db [dbName]', 'Optional name of db', null)
.parse(process.argv);
var dbName = program.db || getDefaultDBName();
var paths = program.args;
if (!paths.length) {
console.log('Need to provide at least one path.');
process.exit(1);
}
// Do the upload!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4035 次 |
| 最近记录: |