search
HomeWeb Front-endJS TutorialNode practical development of a mycli command line tool

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

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"
  },
  • New/ test.jsFile
console.log("mycli命令执行成功");
  • 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命令执行成功");

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. <pre class='brush:php;toolbar:false;'>#!/usr/bin/env node</pre>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
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);

Node practical development of a mycli command line tool

##Ora

Installation

    npm install ora@4.0.3 -S
  • Use test.js
    const ora = require("ora");
    
    // ora
    const spinner = ora({
      text: "安装中..."
    });
    spinner.start();
    setTimeout(() => {
      // spinner.stop();
      spinner.succeed("安装成功");
      // console.log("安装成功");
    }, 2000)
  • 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
  • Use
const commander = require("commander");
// ...
commander.parse(process.argv); // 放在后面
    After the installation is completed,
  • commander
  • will be automatically provided to us Some commands, such as
--help

, let’s test it below:

mycli --help
provides a method to set the version number

commander.version("1.0.0");
    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)
    })
    Now execute the mycli --init
  • test:

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

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

自定义命令方法

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

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

查看帮助

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

Node practical development of a mycli command line tool

inquirer

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

  })

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);
  })
})
  • type是判断类型的 confirm
commander.command("testcon").action(() => {
  inquirer.prompt([
    {
      type: "confirm",
      name: "age",
      message: "是否大于18岁?"
    }
  ]).then((answer) => {
    console.log(answer);
  })
})

输入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);
  })
})

执行 mycli testlist 命令:

Node practical development of a mycli command line tool

下载模板

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

  • 安装

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

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

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"));
  })
})

执行 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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version