官术网_书友最值得收藏!

Getting input from the user inside the command line

To start things off, let's run our app from the Terminal. We'll run it pretty similarly to how we ran it in the earlier sections: we'll start with node (I'm not using nodemon since we'll be changing the input), then we'll use app.js, which is the file we want to run, but then we can still type other variables.

We can pass all sorts of command-line arguments in. We could have a command, and this would tell the app what to do, whether you want to add a note, remove a note, or list a note.

If we want to add a note, that might look as a command shown in the following code:

node app.js add

This command will add a note; we can remove a note using the remove command, as shown here:

node app.js remove

And we could list all of our notes using the list command:

node app.js list

Now, when we run this command, the app is still going to work as expected. Just because we passed in a new argument doesn't mean our app is going to crash:

And we actually have access to the list argument already, we're just not using it inside the application.

To access the command-line arguments your app was initialized with, you'll want to use that process object that we explored in the first chapter.

We can log out all of the arguments using console.log to print them to the screen; it's on the process object, and the property we're looking for is argv.

The argv object is short for arguments vector, or in the case of JavaScript, it's more like an arguments array. This will be an array of all the command-line arguments passed in, and we can use them to start creating our application.

Now save app.js and it'll look like the following:

console.log('Starting app.js');

const fs = require('fs');
const _ = require('lodash');

const notes = require('./notes.js');

console.log(process.argv);

Then we'll rerun this file:

Now, as shown in the preceding command output, we have three items which are as follows:

  • The first one points to the executable for Node that was used.
  • The second one points to the app file that was started; in this case, it was app.js.
  • The third one is where our command-line arguments start to come into play. In it, we have our list showing up as a string.

That means we can access that third item in the array, and that will be the command for our notes application.

主站蜘蛛池模板: 离岛区| 柳河县| 新密市| 荔波县| 广安市| 辽源市| 左权县| 南郑县| 翁源县| 石城县| 莫力| 安丘市| 碌曲县| 新巴尔虎左旗| 东阳市| 武山县| 陵川县| 新野县| 内乡县| 夏河县| 广宗县| 河北区| 南雄市| 榆树市| 宁波市| 会宁县| 泰顺县| 青田县| 简阳市| 蒙阴县| 磴口县| 佳木斯市| 木兰县| 南充市| 泗洪县| 阳西县| 仪征市| 綦江县| 桓仁| 梓潼县| 亚东县|