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

丶灬走出姿态 提交于 2021-01-29 07:40:58

问题


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.


回答1:


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.




回答2:


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. e.g.

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


来源:https://stackoverflow.com/questions/61965755/inquirer-js-exits-the-terminal-before-asking-all-questions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!