Building command line tools using node.js
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
Create a new Node.js project.
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.
Add
#!/usr/bin/env node
to the header of the bin/my-cli.js file.Add
"bin": {"my-cli": "./bin/my-cli.js"},
to package.json, declare us The command to use.Execute
npm link
in the project root directory to create a global commandmy-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");
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-id
attribute
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); }
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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 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

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: $

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

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 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.

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
