In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to develop a node command line tool from scratch". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is a command line tool?
Command line tool (Cmmand Line Interface) referred to as cli, as the name implies, is the tool used in the command line terminal. Our commonly used git, npm, vim and so on are all cli tools. For example, we can simply copy the remote code locally through commands such as git clone.
Why use the cli tool?
As opposed to cli is the graphical user interface (gui), almost all gui tools are used in windows environment, while almost all cli tools are used in linux environment, because the two users are different, gui focuses on ease of use, while cli focuses on efficiency. For programmers familiar with gui and the integrated development environment (IDE), this seems difficult to understand. After all, isn't it more convenient to drag with a mouse?
Unfortunately, the answer is no. Gui may be faster and more convenient for some simple operations. Such as moving files, reading emails, or writing word documents. But if you rely on gui to do all the work, you will miss out on some of the capabilities of the environment, such as automating common tasks or taking advantage of the full functionality of various tools. And you can't combine tools to create custom macro tools. The advantage of gui is what you see is what you get. The disadvantage is what you see is all you get (what you see is what you get).
As a pragmatic programmer, you constantly want to perform special operations (operations that gui may not support). Cli is more appropriate when you want to quickly combine commands to complete a query or some other task. For example: check which js files have not been changed last week:
# cli: find. -name'* .js'- mtime + 7-print # gui: 1. Click and go to "find File", click the "File name" field, type "* .js", and select the "modified date" tab; 2. Then select between. Click start date and type in the start date of the project. 3. Click "end date", type in the date of 1 week ago (make sure you have a calendar at hand), and click "start search"
How to develop a cli tool?
Basically, any mature language can be used to develop cli tools, as a front-end rookie, or JavaScript is more convenient, so we chose node as the development language.
Create a project
# 1. Create a directory: mkdir kid-cli & & cd kid-cli # 2. Since we will eventually publish cli to npm, we need to initialize a package: npm init # 3. Create an index.js file touch index.js # 4. Open the editor (vscode) code.
Install the code command, run VS code and open the command panel (⇧⌘ P), then type shell command to find: Install 'code' command in PATH.
Open the index.js file and add a piece of test code:
#! / usr/bin/env node console.log ('hello worldview')
When the terminal runs the node program, you need to enter the node command first, such as
Node index.js
You can output hello worldview correctly, and the #! / usr/bin/env node at the top of the code tells the terminal that this file is to be executed using node.
Create a command
Generally speaking, cli has a specific command, such as git, code just used, etc. We also need to set a command, which is called kid. How to get the terminal to recognize this command? Quite simply, open the package.json file, add a field bin, and declare a command keyword and the corresponding file to execute:
# package.json. Bin: {"kid": "index.js"},.
If you want to declare multiple commands, just modify this field.
Then we test it and type kid in the terminal, which prompts us:
Zsh: command not found: kid
What causes it? Recall that usually when we use a cli tool, we need to install it first, such as vue-cli, and we need a global installation before using it:
Npm I vue-cli-g
Our kid-cli has not been released to npm and certainly has not been installed, so the terminal does not know this command yet. Usually we want to test a npm package locally, we can use the command: npm link, install the package locally, and let's execute it:
Npm link
And then execute.
Kid
Command, look at the correct output hello world! Yes.
At this point, a simple command-line tool is complete, but this tool is of no use. Don't worry, let's enhance its function bit by bit.
View version information
First of all, check the version information of cli. You want to view the version information with the following command:
Kid-v
There are two questions.
How to get the parameter-v?
How do I get version information?
In the node program, you can get the parameters of the command through process.argv, return as an array, modify the index.js, and output the array:
Console.log (process.argv)
Then enter any command, such as:
Kid-v-h-lalala
The console will output
['/ Users/shaolong/.nvm/versions/node/v8.9.0/bin/node','/ Users/shaolong/.nvm/versions/node/v8.9.0/bin/kid','- venting,'- hacking,'- lalala']
The third parameter of this array is the-v we want.
The second problem is that the version information is usually placed in the version field of the package.json file. As soon as require comes in, the modified index.js code is as follows:
#! / usr/bin/env node const pkg = require ('. / package.json') const command = process.argv [2] switch (command) {case'- vault: console.log (pkg.version) break default: break}
Then we execute kid-v, and we can output the version number.
Initialize a project
Next, let's implement one of the most common functions, initializing a project with cli.
The whole process goes something like this:
Cd to a directory where you want to create a new project
Execute the kid init command and enter the project name when prompted
Cli pulls the template project code through git and copies it to the directory where the project name is located.
In order to implement this process, we need to solve the following problems:
Execute complex commands
In the above example, we get the parameters of the command through process.argv, but when a command has multiple parameters, or when a command such as a new project requires the user to enter a project name (we call it "question and answer"), a simple swith case is stretched. Here we refer to a package that specifically handles command-line interactions: commander.
Npm i commander-save
And then transform index.js.
#! / usr/bin/env node const program = require ('commander') program.version (require ('. / package.json'). Version) program.parse (process.argv)
Running
Kid-h
Will output
Usage: kid [options] [command] Options:-V,-- version output the version number-h,-- help output usage information
Commander has created the help information for us, as well as two parameters-V and-h. The program.version in the above code returns the version number, which is consistent with the previous function. Program.parse passes the command parameters into the commander pipeline and is generally executed in * *.
Add a question and answer operation
Next, let's add the question and answer operation of kid init. Here we need to introduce a new package: inquirer, which can be easily configured to enable cli to support question and answer interaction.
Npm i inquirer-save
Index.js:
#! / usr/bin/env node const program = require ('commander') var inquirer = require (' inquirer') const initAction = () > {inquirer.prompt ([{type: 'input', message:' please enter the project name:', name: 'name'}]) .then (answers = > {console.log (' project name:' Answers.name) console.log ('copying project Please wait a moment)} program.version (require ('. / package.json') .version) program .command ('init') .description (' create project') .action (initAction) program.parse (process.argv)
Program.command can define a command, description adds a description, which is shown in-- help, and action specifies a callback function to execute the command. Inquirer.prompt can receive a set of question and answer objects. The type field indicates the question and answer type, and name specifies the key of the answer. You can get the user's input through name in answers. There are many types of question and answer. Here we use input to let the user enter the project name.
Run kid init, and then you will be prompted for a project name, which will be printed.
Run the shell script
Students who are familiar with git and linux can initialize a project with a few words:
Git clone xxxxx.git-- depth=1 mv xxxxx my-project rm-rf. / my-project/.git cd my-project npm I
So how do you execute shell scripts in node? You only need to install the shelljs package and you can easily do it.
Npm i shelljs-save
Suppose we want to clone the code for the vue-admin-template project on github, install the dependency automatically, modify index.js, and add the logic to execute the shell script in the initAction function:
#! / usr/bin/env node const program = require ('commander') const inquirer = require (' inquirer') const shell = require ('shelljs') const initAction = () > {inquirer.prompt ([{type:' input', message: 'please enter the project name:', name: 'name'}]) .then (answers = > {console.log (' project name:' Answers.name) console.log ('copying project Please wait a moment) const remote = 'https://github.com/PanJiaChen/vue-admin-template.git' const curName =' vue-admin-template' const tarName = answers.name shell.exec (`git clone ${remote}-- depth=1 mv ${curName} ${tarName} rm-rf. / $ {tarName} / .git cd ${tarName} npm I ` (error, stdout, stderr) = > {if (error) {console.error (`exec error: ${error} `) return} console.log (` ${stdout} `) console.log (` ${stderr} `)}) })} program.version (require ('. / package.json') .version) program .command ('init') .description (' create project') .action (initAction) program.parse (process.argv)
Shell.exec can help us execute a script that outputs the result of the script execution in the callback function.
Test our initialization function:
Cd.. Kid init # enter a project name
As you can see, cli has automatically pulled the vue-admin-template code from the github, put it in the specified directory, and helped us install the dependencies automatically.
This is the end of "how to develop a node command line tool from scratch". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.