title: Commander.js - Implementing sub commands that executes when the previous one is finished
body: <p>I'm using <a href="https://github.com/tj/commander.js" rel="nofollow noreferrer">Commander.js</a> to write my own CLI. I managed to write commands that work individually but now I need to implement sub commands but the docs are a bit vague and confusing so I haven't been able to figure out.</p>
  
  <p>What I want is the <code>connect</code> command to connect to a MongoDB instance and when it has done that proceed to execute the <code>get</code> command. How can I achieve this?</p>
  
  <p>These are the commands and <code>package.json</code>:</p>
  
  <p><strong>./package.json</strong>:</p>
  
  <pre><code>{
    ...
    "main": "./commands/my-cli.js",
    "bin": "./commands/my-cli.js",
    ...
  }
  </code></pre>
  
  <p><strong>./commands/my-cli.js</strong>:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p><strong>./commands/my-cli-connect.js</strong>:</p>
  
  <pre><code>function connect(program) {
  
    program
      .command('connect &lt;db&gt; &lt;username&gt; &lt;password&gt;', 'Connects to a database')
      .action((db, username, password) =&gt; {
  
        MongoClient.connect(&lt;some-mongo-url&gt;, {useNewUrlParser: true}, (err, connection) =&gt; {
  
          assert.equal(null, err, 'Failed to connect to MongoDB instance');
  
          // Continue here with the get command
        });
      }); 
  
    program.parse(process.argv);
  }
  
  module.exports = connect;
  </code></pre>
  
  <p><strong>./commands/my-cli-get.js</strong>:</p>
  
  <pre><code>function get(program) {
  
    program
      .command('get &lt;collection&gt;')
      .option('-q,--query &lt;query&gt;', '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;
  </code></pre>
  
  <p>Running <code>my-cli --help</code> shows these available commands:</p>
  
  <pre><code>...
  
  Commands:
    connect &lt;db&gt; &lt;username&gt; &lt;password&gt;  Connects to a database
    help [cmd]                          display help for [cmd]
  </code></pre>
  
  <p>Example command execution that should call both <code>connect</code> and then <code>get</code> when <code>connect</code> has finished connecting:</p>
  
  <pre><code>$ my-cli connect myDb myUser myPass get users -q '{"email": "foo@gmail.com"}'
  </code></pre>
  
  <p>Right now the <code>get</code> command's <code>action</code> function never runs.</p>