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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use