Welcome to GitHub mountain and moon blog: shfshanyue/blog, which contains my problems encountered in practical work, thinking about business and learning in the direction of the full stack
- Chances are you don’t need a server
- Front-end engineering series
- Node advanced series
Shanyue. tech/node/ CLI.ht…
Recently yamatsuki developed a small client tool that parses content from arbitrary urls and generates markdowns: Markdown-read. For my personal public account content acquisition and some quality content collection, welcome Star, download and use.
$markdown https://juejin.cn/post/6924258563862822919 | head - > the author: Wind, Skyler, ZRJ, what ZJ had# # introductionWebpack5 was officially released on October 10, 2020, and has been evolving and iterating rapidly over the past few months. As of January 28, Webpack5 has been updated in 18 minor versions, bringing a number of very attractive new features. According to [website] (HTTP: / / https://webpack.js.org/blog/2020-10-10-webpack-5-release/#general-direction #general-direction #general-direction! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/77ee2267bfa34ef5bf7bb29553a5035c~tplv-k3u1fbpfcp-zoom-1.image) + Improve build performance with persistent disk caching capability + improve long-term caching with better algorithms (reduce cache failure rate for production resources)Copy the code
It’s also interesting to think that developing a command line tool with Node is common at work, so to summarize
Command line tool
What is a command line tool?
The initial impression is that the system commands such as LS and PWD can be executed in the terminal. There are many such commands, which are called system built-in commands. If you use “which” to find out where they came from, you can find out what they are like:
$ which pwd
pwd: shell built-in command
Copy the code
As I understand and use Linux/Unix systems, I have discovered many non-built-in commands:
- top
- ps
- netstat
- dig
- man
Use which to scout out the situation and discover that the path they actually execute is in a bin directory
$ which top
/usr/bin/top
$ which ps
/bin/ps
Copy the code
These bin directories are in the environment variable PATH, and suddenly you see the light. In short: commands for paths in PATH can be executed anywhere else.
export PATH=$HOME/bin:/usr/local/bin:$PATH
Copy the code
What do you seem to be thinking about? Fears of being dominated by environment variables when configuring Java in college? Yes, all language executables have to be placed under PATH, but other languages do it for you automatically, whereas Java lets you do it yourself.
- java
- python
- pip
- node
- npm
The same is true for developing the command line, and the goal of this article is to:
Use Javascript, a language familiar to front-end developers, to develop a command-line tool with the help of the Node environment.
The principle of
Take a look at two command line tools: serve a popular static file server and Markdown a command line that I wrote myself to parse urls into Markdow. Parse the symbolic links to which they point by command
$ ls -lah $(which serve)
lrwxr-xr-x 1 xiange admin 65B 7 12 2020 /usr/local/bin/serve -> .. /.. /.. /Users/shanyue/.config/yarn/global/node_modules/.bin/serve $ ls -lah $(which markdown)
lrwxr-xr-x 1 xiange admin 48B 1 28 20:06 /usr/local/bin/markdown -> .. /lib/node_modules/markdown-read/md-read-cli.jsCopy the code
Here’s how they parse the command line:
- /usr/local/lib/node_modules
- The corresponding binary script is mounted to the PATH PATH as instructed by the bin option in package.json
- Add x permissions to the corresponding binary script (executable file permissions)
In short, command line tools in the Node environment rely on nothing more than the environment variable Path and a symbolic link
From the package. The json
The bin option in package.json to specify the name of the final command line tool
{
"bin": {
"markdown": "./md-read-cli"}}Copy the code
As shown above, markdown is the command that is ultimately executed at the terminal, and./md-read-cli is the file where the command is actually executed.
For final executable command-line tools, Node projects tend to place files in the bin directory, as in the following Typescript configuration:
{
"bin": {
"tsc": "./bin/tsc"."tsserver": "./bin/tsserver"}},Copy the code
An execution environment
For files that can be executed directly, specify the execution environment and add the following line at the beginning:
#! /usr/bin/env node
// code down
Copy the code
What does this sentence mean?
#!
An interpreter is followed to indicate the use of the file/usr/bin/env node
To perform the/usr/bin/env
Is the absolute PATH to env, used to execute commands in the PATH PATH (node command line location is different in various systems, so useenv node
Find the path and execute)env node
At the human level, it can be understood as executionnode
The command
Execute the script using Node
/ / don't write#! /usr/bin/env node$node serve. // Write#! /usr/bin/env node
$ serve .
Copy the code
Parsing command input
$ node cmd.js 1 2 3
Copy the code
// Output: [
// '/usr/local/bin/node',
// '/Users/shanyue/cmd.js',
/ / '1',
/ / '2',
/ / '3',
// ]
process.argv
Copy the code
Get various arguments as input to the command line by parsing process.argv, which also follows the basic rules: format, optional, required, shorthand, description, help, and so on. The command line tool naming protocol article is detailed enough.
// A more tidy command line help $node --help
Usage: node [options] [ script.js ] [arguments]
node inspect [options] [ script.js | host:port ] [arguments]
Options:
- script read from stdin (default if no file name is provided,
interactive mode if a tty)
-- indicate the end of node options
--abort-on-uncaught-exception aborting instead of exiting causes a core file to be generated for
analysis
-c, --check syntax check script without executing
--completion-bash print source-able bash completion script
--cpu-prof Start the V8 CPU profiler on start up, and write the CPU profile to
disk before exit. If --cpu-prof-dir is not specified, write the profile
to the current working directory.
Copy the code
Derived from this on the parsing command parameters of a number of libraries, in the actual work directly use it!
- Yargs: Star 8.5K, weekly downloads 4900K
- Commander: Star 19.7K, weekly downloads 5300K, works of tJ
Use Commander to parse different input instructions
const { program } = require('commander')
// Parse different instruction inputs
program
.option('-d, --debug'.'output extra debugging')
.option('-s, --small'.'small pizza size')
.option('-p, --pizza-type <type>'.'flavour of pizza')
program.parse(process.argv)
const options = program.opts()
console.log(options)
Copy the code
Rich color experience
Most terminals now support color output, and rich color highlighting, like code highlighting, allows users to quickly capture key points. The exception, warning, and success messages are color-coded so that the output of the command line tool is easy to see. Most modern build tools, such as Webpack, also support color output.
The following are two color libraries commonly used in command line tools to support the output of a wide variety of colors.
- chalk
- colors
The following example is Chalk, where Error and Warning messages are represented in different colors
const chalk = require('chalk')
const error = chalk.bold.red
const warning = chalk.keyword('orange')
console.log(error('Error! '))
console.log(warning('Warning! '))
Copy the code
Release and Installation
After the hard work of writing a CLI tool, it’s time to test the results. Publishing to the NPM repository enables everyone to use your command-line tools, which is the most important step
NPM login is required to login to NPM registory before publishing
$ npm publish
Copy the code
After the success of the global download command line tool, began to use, using it to grab my blog home page
$ npm i -g markdown-read
/usr/local/bin/markdown -> /usr/local/lib/node_modules/markdown-read/md-read-cli.js
+ [email protected]
added 102 packages from 72 contributors and updated 10 packages inS $33.15 markdown https://shanyue.tech## [#](# Santsuki's trivial blog entry) Santsuki's trivial blog entryThis blog is a summary of some articles about the problems encountered in front end, back end and operation and maintenance in ordinary work. Later will also do a series of articles for output, such as front-end advanced advanced series, personal server guide series. Personal wechat shanyue94, welcome to add communication## [#](# name origin) Name origin
Copy the code
conclusion
This article explains the following aspects from shallow to deep:
- What is the principle of a globally executable command line tool
- Configuration required to develop a command line tool in Node
- How to parse parameters when developing command-line tools
And according to the practice, developed a small tool to read Markdown from THE URL: Markdown -read, welcome Star, download and use.
In addition, I made a Web version based on this command line, welcome to experience: devtool.tech/html-md