3.6 Getting Input From User

In this lesson, we are going to learn how to get user’s input from command line.

In the past, we run our app by

> node app.js

One way for user to provide information is to append their arguments after the above line, such like

> node app.js remove

remove is an argument passed from user. Later in the app, we will see how to obtain that information and make use of it.

However, even though we don’t do any change, running the above line wouldn’t cause any error. Actually, we already have the access to this argument remove, but we don’t use it inside our application.

Adding the following line to print argument-related information

console.log(process.argv);

Save the app.js and take a moment to re-run the file.

We have new information shown up:

[ '/usr/local/bin/node',
'/Users/xingao/notes-node/app.js',
'remove' ]

The first two lines aren’t so important as the last one, since remove is the argument passed from user and we are willing to deal with that argument inside our app.

This is in fact the third element in an array. To access the third item in an array, as I belive you all know, by process.argv[2]

Therefore, since we have already possessed the access to user’s arguments, we are likely to extend the functionality through their arguments. Here is what we are going to do.

var command = process.argv[2];
console.log('Command: ', command); // reconfirm arg
if (command === 'add') {
console.log('Adding new note');
} else if (command === 'list') {
console.log('Listing all notes');
} else if (command === 'read') {
console.log('Reading note')
} else if (command === 'remove') {
console.log('Removing note')
} else {
console.log('Command not recognized');
}

For example, if we run our app with argument add and list, respectively, we will get the following results

> node app.js add
starting app...
Sarting notes.js
Command: add
Adding new note
> node app.js list
starting app...
Sarting notes.js
Command: list
Listing all notes

It is same as cases in reading note and removing note.

Now we want to get more than one argument from user to proceed a bit of more complicated actions.

For example, node app.js remove --title="study plan" is telling our app to remove the note with title “study plan”. At the meantime, the user would be allowed to format their arguments like this node app.js remove -t="study plan" etc. It is very hard to make use of the third arguments when uncertainty in format comes to play. The good news is we are not going to do that, but in the next time we are going to use a third party module to handle these arguments.