從 1 到完美,用 node 寫一個命令行工具

從 1 到完美,用 node 寫一個命令行工具

1. package.json 中的 bin 字段

如今,無論是前端項目仍是 node 項目,通常都會用 npm 作包管理工具,而 package.json 是其相關的配置信息。前端

node 項目而言,模塊導出入口文件由 package.jsonmain 字段指定,而若是是要安裝到命令行的工具,則是由 package.jsonbin 字段指定。node

1.1 配置單個命令

與包名同名

{
  "name": "pro",
  "bin": "bin/pro.js"
}

這樣安裝的命令名稱就是 prolinux

自定義命令名稱(與包名不一樣名)

{
  "name": "pro-cli",
  "bin": {
    "pro": "bin/pro.js"
  }
}

這樣安裝的命令名稱也是 prowebpack

1.2 配置多個命令

{
  "name": "pro-cli",
  "bin": {
    "pro": "bin/pro.js",
    "mini": "bin/mini.js"
  }
}

這樣安裝就有 promini 兩個命令。git

2. 對應 bin/pro.js 文件的寫法

#!/usr/bin/env node

require('../lib/pro');

與普通的 js 文件寫法同樣,只是前面要加上 #!/usr/bin/env nodegithub

這段前綴代碼叫 shebang,具體能夠參考 Shebang (Unix) - Wikipedia).web

3. 安裝方式

3.1 全局安裝

npm i -g pro-cli

這種安裝方式能夠在命令行全局使用。shell

pro dev

pro build

3.2 本地安裝

npm i --save-dev pro-cli

這種安裝方式須要配合 npm 一塊兒使用,好比:npm

# package.json
{
  "scripts": {
    "dev": "pro dev",
    "build": "pro build"
  }
}

# 使用
npm run dev
npm run build

4. 選擇合適的命令行封裝庫

通常來講,一個命令都會有以下的一些參數:json

  • -v, --version-V, --version: 查看版本號
  • -h, --help: 查看幫助信息

若是徹底本身來寫的,就會很麻煩,尤爲是幫助信息。因此,選擇一個好的命令行封裝庫,可以幫咱們省去不少工做。

用的比較多的:

commander.js 爲例:

4.1 安裝

npm install commander --save

4.2 註冊

const commander = require('commander');

註冊版本號與描述

commander
  .version('0.0.1')
  .description('A cli application named pro');

註冊參數(非子命令參數)

commander
  .option('-p, --peppers', 'Add peppers')
  .option('-P, --pineapple', 'Add pineapple')
  .option('-b, --bbq-sauce', 'Add bbq sauce')
  .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')

註冊子命令

commander
  .command('rm <dir>')
  .option('-r, --recursive', 'Remove recursively')
  .action((dir, cmd) => {
    console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
  })

解析

commander.parse(process.argv);

4.3 使用

查看版本號

pro -V
pro --version

# 打印結果
0.0.1

運行 rm 子命令

pro rm dir

查看幫助(commander 會自動生成)

pro -h
pro --help

# 打印結果
Usage: pro [options]

A cli application named pro

Options:
  -h, --help           output usage information
  -V, --version        output the version number
  -p, --peppers        Add peppers
  -P, --pineapple      Add pineapple
  -b, --bbq            Add bbq sauce
  -c, --cheese <type>  Add the specified type of cheese [marble]
  -C, --no-cheese      You do not want any cheese

更多用法查看 commander.js

5. 經常使用的命令行相關工具庫

5.1 minimist: 解析命令行的參數

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  beep: 'boop' }

更多參考 minimist

5.2 chalk: 讓命令行的字符帶上顏色

圖片描述

更多參考 chalk

5.3 Inquirer.js: 讓命令行與用戶進行交互,如輸入、選擇等

圖片描述

更多參考 Inquirer.js

5.4 shelljs: 跨平臺 Unix shell 命令 的 node 封裝

var shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');

// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}

更多參考 shelljs

5.5 blessed-contrib: 命令行圖表

圖片描述

更多參考 blessed-contrib

5.6 cash: 跨平臺 linux 命令 的 node 封裝

shelljs 功能差很少。

const $ = require('cash');
const out = $.ls('.', {l: true});

更多參考 cash

5.7 prompts: 又一個讓命令行與用戶進行交互的工具

Inquirer.js 功能差很少。

圖片描述

更多參考 prompts

5.8 ora: 命令行加載中圖標

圖片描述

更多參考 ora

5.9 progress: 命令行進度條

downloading [=====             ] 39/bps 29% 3.7s

更多參考 progress

5.10 更多

更多關於命令行的工具庫能夠參考 command-line-utilities

6. 比較經常使用的命令行 APP

命令行相關的應用就不少啦,好比 babelwebpackrollupeslint 等,但這些不單單是命令行工具。

下面介紹一些純命令行應用:

更多純命令行應用能夠參考 command-line-apps

後續

更多博客,查看 https://github.com/senntyou/blogs

做者:深予之 (@senntyou)

版權聲明:自由轉載-非商用-非衍生-保持署名(創意共享3.0許可證

相關文章
相關標籤/搜索