In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to implement a Node.js-CLI development tool". 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!
Initialize the project
First, we will open the CLI interface and initialize a project with npm:
Npm init
Package.json
{"name": "mycli", "version": "1.0.0", "description": "A cli-demo", "main": "index.js", "author": "xmanlin", "license": "MIT"}
Some of them are useless and have been removed.
Custom command
I believe that many friends will find that they have one thing in common when initializing a project with npm, or when building a project with Vue CLI-they all have their own personalized commands, which feels a little cool. So how can we implement our own command, simply add bin to package.json:
{"name": "mycli", "version": "1.0.0", "description": "A cli-demo", "main": "index.js", "bin": {"mycli": ". / index.js"}, "author": "xmanlin", "license": "MIT"}
The function of bin in package.json is to make the set mycli an executable command, and the file executed by the command is the later index.js, all of which can be decided according to your own ideas. Then we will continue to modify the index.js:
Index.js
#! / usr/bin/env nodeconsole.log ("execution succeeded")
The first line here is important, which indicates that index.js is the node executable.
Once the setup is complete, you can install our CLI tool globally:
Npm install-g + mycli@1.0.0added 1 package from 1 contributor in 0.12s
You can see that the global installation is successful. Finally, let's try our command:
Mycli
Output:
Execute successfully interactive command line
Just now, when operating on the command line, the partners used commands with different options, such as npm init and npm install-g, which included some interactive commands, such as npm init provided some commands in the form of input questions and answers when initializing the project. Next, let's add these similar commands to our CLI tool.
We can rely on two libraries for our development: commander.js and Inquirer.js
Commander.js: a complete node.js command line solution. We can use it to quickly write our command line and customize the operation.
Inquirer.js: a collection of regular interactive command line user interfaces, providing Node.js with a beautiful command line interface that is easy to embed. We can use it to quickly write interactive command lines.
The specific usage of these two libraries is introduced too much here. Friends can click on the link of the above name to get familiar with it. It does not take much time, and it is not difficult to use it actually. The latter one does not have a Chinese Readme, but it does not prevent you from searching for whether it is correct.
Define option
Let's first implement similar command options like npm-v and node-v.
Install commander.js first:
Npm install commander
Then introduce commander.js and modify index.js
#! / usr/bin/env nodeconst {program} = require ('commander'); / / method of splitting strings into arrays function strToArr (value, preValue) {return value.split (',')} / / cli version program.version (require ('. / package'). Version,'- v,-- the latest version of version', 'cli') / / set the option program .option ('- d,-- debug', 'debug') .option ('- l,-- list', 'split the string into arrays', strToArr) .action ((options) Command) = > {/ / logical processing if (options.debug) {console.log ("debugging successful")} if (options.list! = = undefined) {console.log (options.list)}})) / / process the parameter program.parse (process.argv) entered on the command line
Let's try the command options you just set:
Mycli-d
Output:
Debug successfully
Enter:
Mycli-l 1pm 2pm 3
Output:
['1','2','3']
It has been defined for us in commander.js-the help option:
Mycli-h
Output:
Usage: index [options] Options:-v,-- the latest version of version cli-d,-- debug debug-l,-- list splits the string into arrays-h,-- help display help for command
With the-- help option, we can clearly see how many commands there are in mycli.
Set subcommand
In project development, we sometimes use commands like npm run xxx, where run is equivalent to a subcommand of npm. Here we can also set a similar subcommand for mycli:
Const {program} = require ('commander');. / / create file command line program .command (' create') .description ('create a file') .action ((filename) = > {console.log (file)}). / / process the parameter program.parse (process.argv) entered by the command line
Command ('create') creates a create subcommand of mycli, followed by a required parameter.
Enter:
Mycli create file
Output
File
The subcommand was created successfully.
Create a project file using the command line
We can now define options and set commands. Then we can actually do something and use the command line to create files for the project.
Simply design a process:
Create a template file
Let's first create a templates folder, and then write some common template files in it. The template file here is applied to the template string, which is structured as follows:
ReactClass.js
Module.exports = function (className) {return `import * as React from 'react';export class ${className} extends React.Component {constructor (props) {super (props); this.state = {}} componentDidMount () {} render () {return ()} `}
VueTemplate.js
Module.exports = function () {return `export default {data () {return {}} methods: {}} `}
Index.js
Const reactClass = require ('. / reactClass'); const vueTemplate = require ('. / vueTemplate'); module.exports = [{name: 'reactClass', src: reactClass}, {name:' vueTemplate', src: vueTemplate}]
After the template file is created, let's put it aside and use it later.
Create interactive command lines and invoke templates
When we enter the mycli create file command, we need to get the effect in the following image, we can manually choose up and down, that is, it can be called an interactive command.
The other library we mentioned above, Inquirer.js, will be used here.
First of all, it must be installed.
Npm install inquirer
Introduce and modify index.js in our root directory:
#! / usr/bin/env nodeconst {program} = require ('commander'); const inquirer = require (' inquirer'); / / introduce the template file const templates = require ('. / templates/index'); / / Command line selection list let prompList = [{type:'list',name: 'template',message:' please select the template you want to generate?' , choices: templates,default: templates [0]}]. / / create a file command line program .command ('create') .description ('create a file') .action (async (filename) = > {const res = await inquirer.prompt (prompList) console.log (res)}) / / process the parameter program.parse (process.argv) entered by the command line
Next, we enter on the command line:
Mycli create file
You can get the effect shown above.
Then select the first one and enter:
You can see that the name of the template we selected is output. The next step is to create the actual file.
Create a project file
To create a file, you need to call node.js 's fs-related api, and then modify the index.js:
/ / processing file const fs = require ("fs") . / / create file command line program .command ('create') .description ('create a file') .action (async (filename) = > {const res = await inquirer.prompt (prompList) if (res.template = 'reactClass') {templates.forEach ((item) = > {if (item.name =' reactClass') {fs.writeFile (`. / ${filename} .jsx`, item.src (filename)) Function (err) {if (err) {console.log ('creation failed:', err)} else {console.log (`file created successfully! ${filename} .jsx`) }})}} if (res.template = 'vueTemplate') {templates.forEach ((item) = > {if (item.name =' vueTemplate') {fs.writeFile (`. / ${filename} .vue`, item.src () Function (err) {if (err) {console.log ('creation failed:', err)} else {console.log (`file created successfully! ${filename} `);}}).
We type mycli create file on the command line again, and then select a template.
Output:
File created successfully! File.jsx
At the same time, we can see that a new file.jsx file has been added under the project root:
When you open file.jsx, you can see that the class name of the file has been filled in accordingly. Not only that, because our mycli is installed globally, it can be said that anywhere on the computer, as long as we type mycli create file, we can get the file.jsx file in the current directory. This means that when we develop some projects, we don't have to copy and paste, delete and modify them.
It can be done with just one line of command.
More Featur
Now that you can create files, can you create a folder? The answer is yes, just continue to add commands:
. / / create folder command line program .command ('create-f') .description ('create a folder') .action ((folder) = > {if (fs.existsSync (folder)) {console.log ('folder already exists')} else {fs.mkdirSync (folder); console.log ('folder created successfully')});.
Then type mycli create-f xxx on the command line, and you can also create the folder you want to name.
"how to implement a Node.js-CLI development tool" content is introduced here, 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.