Node.js commander,带有可选的+;可变参数

Node.js commander,带有可选的+;可变参数,node.js,node-commander,Node.js,Node Commander,我把头撞在墙上,试图让node的commander模块以我想要的方式解析参数 我想上传一个文件列表到一个命名的数据库。有一个默认的数据库名称,因此用户不需要包含数据库参数 我希望此命令按如下方式工作: >>> ./upload.js --db ReallyCoolDB /files/uploadMe1.txt /files/uploadMe2.txt (uploads "uploadMe1.txt" and "uploadMe2.txt" to database "Really

我把头撞在墙上,试图让node的
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)
如何使用
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);
commander
命令行处理模块的文件在其第二段中回答了您的用例:


commander的选项是用.option()方法定义的,也可用作选项的文档。下面的示例解析process.argv中的参数和选项,将剩余的参数保留为program.args数组,这些参数没有被选项使用

那么,用
commander
接受可选参数+非空列表的正确方法是什么?我是否应该使用commander解析可选参数,然后手动解析
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!