简体   繁体   中英

what does `program.parse(process.argv)` do in commander.js?

I want to user commander.js and inquirer.js to ask questions and collect the answer to create a User instance:

// index.js
const mongoose = require('mongoose');
const User = require('./model/user')
const {addUser,listAllUsers,findUserByEmail,updateUser,deleteUser} = require('./model_methods/user_methods')
const { program } = require('commander');
var inquirer = require('inquirer');

// connect to DB
const db = mongoose.connect('mongodb://localhost:27017/myImportantDates', {
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
});

const questions = [
    {
      type: 'input',
      name: 'email',
      message: 'user email'
    },
    {
      type: 'input',
      name: 'name',
      message: 'user name'
    },
    {
      type: 'input',
      name: 'password',
      message: 'user password'
    },
  ];



program
   .version('0.0.1')
   .description('The important dates app');

program
   .command('add')
   .alias('a')
   .description('Add a user')
   .action(
       inquirer
         .prompt(questions)
         .then( answers => {
            addUser(answers)
          })
          .catch(err =>{
            console.log(error) 
          })
   )
program.parse(process.argv);

When I run it with node index.js add , the questions array ask one question and quit:

@DESKTOP-5920U38:/mnt/c/Users/myApp$ node index.js add
? user email 
@DESKTOP-5920U38:/mnt/c/Users/myApp$ 

When I delete program.parse(process.argv) , however, everything works fine, it can return me the new User instance.

I check the documents: https://github.com/tj/commander.js/ Still have no idea what happened. Does anybody know more about this??

What I found just now is that if I put program.parse(process.argv) in the beginning like this in the first set up of the program instance:

program
   .version('0.0.1')
   .description('The important dates app')
   .parse(process.argv);

It works too. But I still don't know why the order matters.

In Node.js, process.argv is an array containing the command line arguments passed when the Node.js process was launched . So, program.parse(process.argv) parses the the command line options for arguments, which is bypassing your inquierer.js prompt. You can leave it out.

program.parse(process.argv) is called after setting up your program. It takes the command line arguments ( process.argv ) and parses them using your declared program, displaying errors or calling action handlers etc.

Based on your example code, an issue is the action handler takes a function parameter. eg

.action(() => {
   // code goes here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM