Table of Contents
Tool Description
Goal
Preparation
Installation dependencies
Build release process automation
Add new features: configuration check
Last step
Example code
Conclusion
Home Web Front-end JS Tutorial Building command line tools using node.js

Building command line tools using node.js

Apr 10, 2018 pm 05:04 PM
javascript node.js Command Line

The content of this article is to use node.js to build command line tools. It has certain reference value. Friends in need can refer to it


Tool Description

  • inquirer.js: A node.js module that encapsulates common command line interactions. This module can easily build a new command line application.

  • shell.js: Cross-platform unix shell command module.

  • Node version: Since the asynchronous method of inquirer.js returns Promise by default, it is recommended to use node.js>=8.

Goal

There are a large number of projects at work that need to be tested, compiled, updated version number, submitted, and even the commands executed are the same in the last step before going online. Here We use command line tools to automate these steps with one click and perform pre-checks to prevent errors and omissions.

Preparation

  1. Create a new Node.js project.

  2. Create the file bin/my-cli.js. The node.js project usually places the cli entry in the bin directory and other modules in the lib directory.

  3. Add #!/usr/bin/env node to the header of the bin/my-cli.js file.

  4. Add "bin": {"my-cli": "./bin/my-cli.js"}, to package.json, declare us The command to use.

  5. Execute npm link in the project root directory to create a global command my-cli.

Slightly modify my-cli.js, add the code console.log("I am a cli tool!"), and then Open the console and run the my-cli command. If you see the console output I am a cli tool!, it means success.

Installation dependencies

First install the two main dependent modules (please refer to the official documentation for the use of these two modules)

npm install inquirer shelljs

Build release process automation

The next step is to implement the automation of testing, updating version numbers, building, and automatically submitting releases

const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

const { version } = await inquirer.prompt([
  {
    type: 'list',
    name: 'version',
    message: '版本号更新方式:',
    choices: [
      {
        name: `v${semver.inc(pkg.version, 'patch')}: Fix Bugs / Patch`,
        value: 'patch'
      },
      {
        name: `v${semver.inc(pkg.version, 'minor')}: Release New Version`,
        value: 'minor'
      },
    ]
  }
]);
// 拉取最新版本
shelljs.exec('git pull');
// 运行测试
shelljs.exec('npm test');
//通过npm version更新版本号,但不自动添加git tag,而是在构建完成后由cli工具添加
shelljs.exec(`npm version ${version} --no-git-tag-version`);
// 构建
shelljs.exec('npm run build');
// 提交发布代码
const nextVersion = semver.inc(pkg.version, version);
shelljs.exec('git add . -A');
shelljs.exec(`git commit -m "build: v${nextVersion}"`)
shelljs.exec(`git tag -a v${nextVersion} -m "build: ${nextVersion}"`);
shelljs.exec("git push")
shelljs.exec("git push --tags");
Copy after login

Add new features: configuration check

Next add a function to my-cli:

When checking the check-baidu- of the my-cli object in package.json When the id attribute is true, check whether the config.json of the project exists baidu-idattribute

if (pkg['my-cli'] && pkg['my-cli']['check-baidu-id']) {
  const configPath = path.join(process.cwd(), 'config.json');
  if (!fs.existsSync(configPath)) {
    shelljs.echo('找不到config.json');
    shelljs.exit(1);
  }
  const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  if (!config['baidu-id']) {
    shelljs.echo('config.json缺少属性[baidu-id]');
    shelljs.exit(1);
  }
Copy after login

Last step

Such a simple cli program has been implemented. It automates the build and release process, and also performs configuration checks before building and releasing.

In actual projects, in order to improve the stability of the program, it is also necessary to add functions such as checking whether package.json exists in the current project, preventing json parsing errors, and confirming before execution. For details, see the sample code.

Example code

Address: https://github.com/Aturan/node-cli-example

Conclusion

Although the above functions use shell It can be implemented, but writing code is not so convenient and fast, and once more complex problems are encountered, it will be very troublesome to implement them using the shell, and maintenance is also a problem.

PS. In fact, you can also use python. For Ubuntu, it is an advantage that the system comes with Python. It can be used directly on the server without installing an environment. In addition, Python also has an Inquirer module.

Related recommendations:

Example details how node.js obtains SQL Server database

Node.js module system

The above is the detailed content of Building command line tools using node.js. 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

Video Face Swap

Video Face Swap

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

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Learn how to use the command line tool sxstrace.exe effectively Learn how to use the command line tool sxstrace.exe effectively Jan 04, 2024 pm 08:47 PM

Many friends who use win10 system have encountered this problem when playing games or installing the system. The application cannot be started because the parallel configuration of the application is incorrect. For more information, see the application event log, or use the command line sxstrace.exe tool. This may be because the operating system does not have corresponding permissions. Let’s take a look at the specific tutorial below. Tutorial on using the command line sxstrace.exe tool 1. This problem usually occurs when installing programs and games. The prompt is: The application cannot be started because the parallel configuration of the application is incorrect. For more information, see the application event log, or use the command line sxstrace.exe tool. 2. Start →

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Upgrade Ubuntu 20.04 to 22.04 via command line Upgrade Ubuntu 20.04 to 22.04 via command line Mar 20, 2024 pm 01:25 PM

This article details the steps to upgrade Ubuntu 20.04 to 22.04. For users using Ubuntu 20.04, they have missed the new features and advantages brought by version 22.04. In order to get a better experience and security, it is recommended to upgrade to a newer Ubuntu version in time. Ubuntu22.04 is codenamed "Jamie Jellyfish", let's explore how to get the latest LTS version! How to upgrade Ubuntu 20.04 to 22.04 via the command line Mastering the command line will give you an advantage. While it is possible to update Ubuntu via the GUI, our focus will be via the command line. First, let’s check the currently running version of Ubuntu using the following command: $

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Detailed explanation of python command line parameters Detailed explanation of python command line parameters Dec 18, 2023 pm 04:13 PM

In Python, parameters can be passed to scripts via the command line. These parameters can be used inside scripts to perform different actions based on different inputs. Detailed explanation of Python command line parameters: 1. Positional parameters: parameters passed to the script in order on the command line. They can be accessed through position inside the script; 2. Command line options: parameters starting with - or -, usually Used to specify specific options or flags for the script; 3. Pass parameter values: Pass parameter values ​​through the command line.

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

A first look at Django: Create your first Django project using the command line A first look at Django: Create your first Django project using the command line Feb 19, 2024 am 09:56 AM

Start the journey of Django project: start from the command line and create your first Django project. Django is a powerful and flexible web application framework. It is based on Python and provides many tools and functions needed to develop web applications. This article will lead you to create your first Django project starting from the command line. Before starting, make sure you have Python and Django installed. Step 1: Create the project directory First, open the command line window and create a new directory

See all articles