This article describes how to use nodejs to develop cli project instances. This article describes how to use generator-cli-starter to develop cli projects. For more information, see 1. use the default option to install nodejs in minutes
2. run sudo npm install-g yo to install yeoman every minute.
3. use sudo npm install-g generator-cli-starter to install cli to develop scaffolding
OK. Now we can use the yo cli-starter command to start our cli development journey.
Create a cli project
The code is as follows:
Yo cli-starter
Enter the project name and command name as prompted to create the cli project. In subsequent tutorials, we will use hi as your command name. if you use another command name, replace it
Let's try first
Enter the following command in the command line (if you are not using hi, replace it with caution)
The code is as follows:
Hi
The effect is as follows:
Try a common command?
Next we will develop a command like ls and ls-all. here we need to use a node module commander to install it first:
Go to the root directory of the project and run npm install -- save commander,
Use your favorite editor to open bin/hi. js and replace the original code with the following content:
The code is as follows:
#! /Usr/bin/env node
'Use strict ';
Var program = require ('commander ');
Program
. Version ('0. 0.1 '); // declare the version number of hi.
Program
. Command ('list') // declare that a command under hi is called list
. Description ('list files in current working directory') // describes the list command.
. Option ('-a, -- all', 'whether to display hidden files') // set the parameters of the list command.
. Action (function (options) {// implementation body of the list command
Var fs = require ('Fs ');
// Obtain the file information in the current running Directory
Fs. readdir (process. cwd (), function (err, files ){
Var list = files;
If (! Options. all) {// check whether the -- all or-a parameter is provided by the user. If no parameter is provided, the files starting with. are filtered out.
List = files. filter (function (file ){
Return file. indexOf ('.')! = 0;
});
}
Console. log (list. join (''); // The console prints all file names
});
});
Program. parse (process. argv); // start parsing the user input command
Okay. now, let's try the command we just wrote,
The code is as follows:
Hi-V
Hi list
The code is as follows:
Hi list-
How to publish
First, create a project on Github and synchronize the code we just wrote.
Then run the npm publish command to release your cli to npm.
Then other users can install your command locally using npm install-g [project name ].