Table of Contents
Initialization
下载模板
代码地址
Home Web Front-end JS Tutorial Node practical development of a mycli command line tool

Node practical development of a mycli command line tool

Jun 06, 2022 pm 06:58 PM
nodejs node.js node

This article will take you step by step to understand a node actual combat, and talk about how to make a mycli command line tool/scaffolding based on node. I hope it will be helpful to everyone!

Node practical development of a mycli command line tool

Initialization

First make sure there is a node.js environment on your computer

Execute the following code on the command line to initialize a package.json file

npm init -y
Copy after login

At this time, an error will definitely be reported when the command line executes mycli.

Node practical development of a mycli command line tool

Configure custom commands

package.json Add bin field, associated myclicommand

  • Each command corresponds to an executable file
  "bin": {
    "mycli": "./test.js"
  },
Copy after login
  • New/ test.jsFile
console.log("mycli命令执行成功");
Copy after login
Copy after login
  • requires the install installation command, but the project has not yet been published to npm, so use npm link## for the time being. #Command, associate the mycli command to the global world.
At this point, if you execute the command line

mycli, no more errors will be reported.

Node practical development of a mycli command line tool

Script configuration

test.js file:

console.log("mycli命令执行成功");
Copy after login
Copy after login

Then execute

mycli, an error pop-up window will appear

Node practical development of a mycli command line tool

This is because when executing the

mycli command, it is equivalent to Let the computer execute this file, but the computer system cannot directly execute the js file. This requires us to add a configuration to the first line of the script code to specify the node.js## on the computer. #Program to execute this js script file. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>#!/usr/bin/env node</pre><div class="contentsignin">Copy after login</div></div>Due to changing the execution environment, you need to delete the previously linked files. The file location may be

C:\Program Files\nodejs\node_modules

. Find mycli and delete it. , and then execute npm link again. Now execute

mycli

on the console, and you can see that the console prints correctly.

Usage of related toolkits

    Chalk
  • Command line output colorful fonts
  • Ora
  • The effect of loading is similar to the progress library
  • commander
  • Design command
  • inquirer
  • Interactive functions (such as: asking questions.. .)

Chalk

Install
  • npm install chalk@4.1.2 -S
    Copy after login
Use test. js
  • const chalk = require("chalk");
    
    // chalk
    // const hello = chalk.red("hello");
    // const hello = chalk.blue.bgRed("hello");
    // const hello = chalk.blue.bgYellow("hello");
    const hello = chalk.rgb(200, 200, 200).bgRgb(0, 200, 3)("hello");
    console.log(hello);
    Copy after login

Node practical development of a mycli command line tool

##Ora

Installation

    npm install ora@4.0.3 -S
    Copy after login
  • Use test.js
    const ora = require("ora");
    
    // ora
    const spinner = ora({
      text: "安装中..."
    });
    spinner.start();
    setTimeout(() => {
      // spinner.stop();
      spinner.succeed("安装成功");
      // console.log("安装成功");
    }, 2000)
    Copy after login
  • Commonly used api
  • start
      Start loading
    • stop
    • Stop loading
    • succeed
    • End loading with successful style

Node practical development of a mycli command line tool##commander

Commands commonly used in development, such as vue -V

git --version

vue Create and other commands, if you want to implement such commands, you need to use the commander library. The -V

--help

etc. after the command used can be understood as the parameters of the command. Then we need to obtain these parameters and judge by Different parameters are used to handle different events. In the node environment, you can get this parameter through

process.argv

. The commander library helps us encapsulate some methods without us having to judge the instructions carried by the user's input. Installation

npm install commander@8.2.0 -S
Copy after login
  • Use
const commander = require("commander");
// ...
commander.parse(process.argv); // 放在后面
Copy after login
    After the installation is completed,
  • commander
  • will be automatically provided to us Some commands, such as
--help

, let’s test it below:

mycli --help
Copy after login
provides a method to set the version number

commander.version("1.0.0");
Copy after login
    Execute
  • mycli -V
  • You can see that the console prints the
1.0.0

version number. Custom command method

commander.option(command name, description, callback function)

Some of the functions written above are configured to the --init

command:
  • commander.option("--init", "this is init", () => {
      // chalk
      // const hello = chalk.red("hello");
      // const hello = chalk.blue.bgRed("hello");
      // const hello = chalk.blue.bgYellow("hello");
      const hello = chalk.rgb(200, 200, 200).bgRgb(0, 200, 3)("hello");
      console.log(hello);
    
      // ora
      const spinner = ora({
        text: "安装中..."
      });
      spinner.start();
      setTimeout(() => {
        // spinner.stop();
        spinner.succeed("安装成功");
        // console.log("安装成功");
      }, 1000)
    })
    Copy after login
    Now execute the mycli --init
  • test:

  • 在指令中传递参数的写法
commander.option("--number <num>", "log a number", (num) => {
  console.log(num);
})
Copy after login

<参数名>表示必传的参数,[参数名]表示非必传的参数。控制台输入mycli --number 100回车,可以看到会输出100

自定义命令方法

commander.command("create <projectName>").action((projectName)=>{
  console.log(projectName);
})
Copy after login

执行 mycli create xx 回车,控制台可以看到 输出了xx

查看帮助

执行 mycli --help,可以看到我们刚才配置的指令和命令都出现在了帮助列表里。

Node practical development of a mycli command line tool

inquirer

  • 安装
npm install inquirer -S
Copy after login
  • prompt提问的方法
  inquirer.prompt([
    {
      type: "input",
      name: "username",
      message: "请输入用户名:"
    }
  ]).then((answer)=>{

  })
Copy after login

type表示问题的类型,取值可能是:input, number, password, editor等。

answer{username: 输入的值}

  • type是输入类型的 input
const inquirer = require("inquirer");

commander.command("add user").action(() => {
  inquirer.prompt([
    {
      type: "input",
      name: "username",
      message: "请输入用户名:"
    }
  ]).then((answer) => {
    console.log(answer);
  })
})
Copy after login
  • type是判断类型的 confirm
commander.command("testcon").action(() => {
  inquirer.prompt([
    {
      type: "confirm",
      name: "age",
      message: "是否大于18岁?"
    }
  ]).then((answer) => {
    console.log(answer);
  })
})
Copy after login

输入yn来进行判断。

Node practical development of a mycli command line tool

  • type是单选类型 list
commander.command("testlist").action(() => {
  inquirer.prompt([
    {
      type: "list",
      name: "lib",
      message: "选择用到的框架:",
      choices: [
        "vue2",
        "vue3",
        "react",
        "svelte",
      ]
    }
  ]).then((answer) => {
    console.log(answer);
  })
})
Copy after login

执行 mycli testlist 命令:

Node practical development of a mycli command line tool

下载模板

  • download-git-repo是一个拉取代码的工具。

  • 安装

npm install download-git-repo@3.0.2 -S
Copy after login
  • 使用
const downgit = require("download-git-repo");

downgit("github:kongcodes/vue3-vant", downUrl, { clone: false }, function (err) {
    console.log(err)
})
Copy after login

downgit方法里面的第一个参数理解为在github上面下载kongcodes用户的vue3-vant项目模板。第二个参数downUrl 为要将模板下载到什么目录下。第三个参数clone 是否要用git clone下载。第四个参数 为下载完成执行的一些事情。

  • 结合command方法使用
commander.command("create <projectName>").action((projectName) => {
  const spinner = ora({
    text: "正在下载https://github.com/kongcodes/vue3-vant..."
  });
  spinner.start();
  fs.mkdirSync(`./${projectName}`);
  const downUrl = `${process.cwd()}\\${projectName}`;
  downgit("github:kongcodes/vue3-vant", downUrl, { clone: false }, function (err) {
    if (err) throw err;
    spinner.stop();
    console.log(chalk.green("downgit success"));
  })
})
Copy after login

执行 mycli create pro 回车,会在当前目录下创建pro目录,下载vue3-vant模板到这个目录里。

代码地址

https://github.com/kongcodes/mycli

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Node practical development of a mycli command line tool. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles