我正在使用Commander.js编写我自己的 CLI。我设法编写了单独工作的命令,但现在我需要实现子命令,但文档有点模糊和混乱,所以我无法弄清楚。
我想要的是connect
连接到 MongoDB 实例的命令,当它完成后继续执行get
命令。我怎样才能做到这一点?
这些是命令和package.json
:
./package.json:
{
...
"main": "./commands/my-cli.js",
"bin": "./commands/my-cli.js",
...
}
./commands/my-cli.js:
const commander = require('commander');
const program = new commander.Command();
const connect = require('./my-cli-connect');
const get = require('./my-cli-get');
// Initialize each command
connect(program);
get(program);
./commands/my-cli-connect.js:
function connect(program) {
program
.command('connect <db> <username> <password>', 'Connects to a database')
.action((db, username, password) => {
MongoClient.connect(<some-mongo-url>, {useNewUrlParser: true}, (err, connection) => {
assert.equal(null, err, 'Failed to connect to MongoDB instance');
// Continue here with the get command
});
});
program.parse(process.argv);
}
module.exports = connect;
./commands/my-cli-get.js:
function get(program) {
program
.command('get <collection>')
.option('-q,--query <query>', 'Search terms', jsonParser, {})
.description('Returns documents from a MongoDB collection')
.action(action);
program.parse(process.argv);
function action(collection, options) {
// This never runs
console.log('hello world');
}
}
module.exports = get;
运行my-cli --help
显示这些可用命令:
...
Commands:
connect <db> <username> <password> Connects to a database
help [cmd] display help for [cmd]
应该同时调用两者connect
以及get
何时connect
完成连接的示例命令执行:
$ my-cli connect myDb myUser myPass get users -q '{"email": "foo@gmail.com"}'
现在该get
命令的action
功能永远不会运行。