用Nodejs開發命令行工具

前言

找到合適的工具包,開發nodejs命令行工具是很容易的javascript

準備工做

  • nodejs v6.10.1
  • npm v3.10.10

版本號是我當前使用的版本,可自行選擇html

Hello World

分4步:java

  • index.js
  • package.json
  • 根目錄下執行npm link
  • 執行命令nhw => hello world

touch index.js建立一個index.js文件,內容以下:node

#! /usr/bin/env node

console.log('hello world')複製代碼

npm init建立一個package.json文件,以後修改爲以下:git

{
    "name": "npmhelloworld", 
    "bin": {
        "nhw": "index.js" 
    },
    "preferGlobal": true,
    "version": "1.0.0",
    "description": "",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "jerryni <jerryni2014@gmail.com>",
    "license": "ISC"
}複製代碼

內容詳解

index.js

#! /usr/bin/env nodegithub

stackoverflow.com/questions/3…shell

這句話是一個shebang line實例, 做用是告訴系統運行這個文件的解釋器是node;
好比,原本須要這樣運行node ./file.js,可是加上了這句後就能夠直接./file.js運行了npm

package.json

{
    // 模塊系統的名字,如require('npmhelloworld')
    "name": "npmhelloworld", 
    "bin": {
        "nhw": "index.js" // nhw就是命令名 ,index.js就是入口
    },

    // 加入 安裝的時候, 就會有-g的提示了
    "preferGlobal": true,


    // 去掉main: 'xxx.js' 是模塊系統的程序入口
    "version": "1.0.0",
    "description": "",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "jerryni <jerryni2014@gmail.com>",
    "license": "ISC"
}複製代碼

執行後,控制檯裏面會有如下輸出:json

/usr/local/bin/nhw -> /usr/local/lib/node_modules/npmhelloworld/index.js
/usr/local/lib/node_modules/npmhelloworld -> /Users/nirizhe/GitHub/npmhelloworld複製代碼

解釋:建立了2個軟連接分別放到系統環境變量$PATH目錄裏,nhw命令和npmhellworld模塊。npm link在用戶使用的場景下是不須要執行的,用戶使用npm i -g npmhellworld命令安裝便可。bash

發佈項目到npm官網供你們使用

設置npm用戶名,沒有的話先到npm官方網站註冊一個:

npm set init.author.name "Your Name"
npm set init.author.email "you@example.com"
npm set init.author.url "http://yourblog.com"

npm adduser複製代碼

項目根目錄運行:

npm publish

注意:

每次發佈須要修改package.json中的版本號,不然沒法發佈

如何處理命令行參數

當下比較流程的幾個工具對比

這邊使用yargs

npm install --save yargs

請看以前我實戰一段代碼

大概是這個樣子:

var argv = yargs
    .option('name', {
        type: 'string',
        describe: '[hostName] Switch host by name',
        alias: 'n'
    })
    .option('list', {
        boolean: true,
        default: false,
        describe: 'Show hostName list',
        alias: 'l'
    })
    .option('close', {
        type: 'string',
        describe: 'close certain host',
        alias: 'c'
    })
    .example('chost -n localhost', 'Switch localhost successfully!')
    .example('chost -c localhost', 'Close localhost successfully!')
    .example('chost -l', 'All host name list: xxx')
    .help('h')
    .alias('h', 'help')
    .epilog('copyright 2017')
    .argv複製代碼

效果:

yargs
yargs

單元測試

推薦使用mocha

var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});複製代碼

執行

$ ./node_modules/mocha/bin/mocha

  Array
    #indexOf()
      ✓ should return -1 when the value is not present


  1 passing (9ms)複製代碼

讓你的項目顯得正規(github badges)

實際效果就是這些小圖標:

badges
badges

這裏能夠找到各式各樣的badges:
github.com/badges/shie…

持續集成(CI)和代碼覆蓋率

travis
travis

Coverage Status
Coverage Status

travis-ci:

  • 用github賬號登陸,這時網站上列出你github上的項目
  • 在項目根目錄放.travis.yml這個文件, 並寫好簡單的配置
    language: node_js
    node_js:
    - "6"複製代碼
  • 在項目的package.json中添加測試腳本, 由於travis默認會執行npm test
    "scripts": {
      "test": "mocha"
    }複製代碼

在travis設置成功後,繼續覆蓋率的處理:

  • 安裝2個依賴

npm install istanbul coveralls --save-dev

  • travis的配置文件中添加
    language: node_js
    node_js:
    - "6"
    after_script:
    - npm run coverage複製代碼
  • 修改package.json中的測試腳本
    "scripts": {
      "test": "node ./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha",
      "coverage": "cat ./coverage/lcov.info | coveralls"
    }複製代碼

經常使用的庫

shelljs

Portable Unix shell commands for Node.js
在nodejs裏用unix命令行

chalk

Terminal string styling done right
給命令行輸出上色

參考資料

javascriptplayground.com/blog/2015/0…
medium.freecodecamp.com/writing-com…
www.ruanyifeng.com/blog/2015/0…
gist.github.com/coolaj86/13…

相關文章
相關標籤/搜索