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.