Use nodejs to develop cli project instances and nodejscli project instances
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
Copy codeThe 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)
Copy codeThe 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:
Copy codeThe 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,
Copy codeThe Code is as follows:
Hi-V
Hi list
Copy codeThe 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 ].