DIV CSS 佈局教程網

詳解如何使用 Node.js 開發自定義命令行工具
編輯:關於JavaScript     

Node.js 極大推動了前端開發的自動化,我們可以用各種工具鏈簡化開發、生成生產構建,例如運行 sass src/sass/main.scss dist/css/main.css 即可編譯樣式。但在實際項目中,我們常有特定需求,需要打造自己的命令行工具。本文記錄如何從零開始創建一個 Node 命令行工具。

一、Hello World

新建 bin 目錄,在其中創建名為 helper 的文件:

 #!/usr/bin/env node
console.log('hello world');

賦予執行權限並運行:

 $ chmod 755 ./bin/helper
$ ./bin/helper
hello world

二、創建符號鏈接

為了能在全局直接以 helper 命令調用,需要在 package.json 中添加 bin 字段:

 {
    "name": "helper",
    "bin": {
        "helper": "bin/helper"
    }
}

然後在工程目錄下執行 npm link,為當前模塊創建符號鏈接:

 $ npm link
/node_path/bin/helper -> /node_path/lib/node_modules/myModule/bin/helper
/node_path/lib/node_modules/myModule -> /Users/ipluser/myModule

此後即可直接使用 helper 命令。

三、引入 commander 模塊

為高效編寫命令行工具,可借助 TJ 的 commander 模塊:

 $ npm install --save commander

修改 helper 文件,添加版本信息:

 #!/usr/bin/env node
var program = require('commander');
program
    .version('1.0.0')
    .parse(process.argv);

此時 helper -h 與 helper -V 已可正常工作,commander 內置了 -h, --help 和 -V, --version 兩個命令。

四、創建自定義命令

創建 helper hello <author> 命令。先在 helper 文件中聲明命令:

 #!/usr/bin/env node
var program = require('commander');
program
    .version('1.0.0')
    .usage('<command> [options]')
    .command('hello', 'hello the author')
    .parse(process.argv);

再在 bin 目錄下新建 helper-hello 文件:

 #!/usr/bin/env node
console.log('hello author');

五、解析輸入參數

希望 author 由用戶動態輸入,需解析 process.argv:

 #!/usr/bin/env node
var program = require('commander');
program.parse(process.argv);
const author = program.args[0];
console.log('hello', author);

六、添加提示信息

當用戶未輸入 author 時,應提示用法。借助 program.on('--help') 與 program.help() 即可實現:

 #!/usr/bin/env node
var program = require('commander');
program.usage('<author>');
program.on('--help', function () {
    console.log(' Examples:');
    console.log(' $ helper hello ipluser');
    console.log();
});
program.parse(process.argv);
(program.args.length < 1) && program.help();
const author = program.args[0];
console.log('hello', author);

這樣,當用戶只輸入 helper hello 或加上 -h 時,終端就會顯示友好的幫助信息。

總結

以上就是從零打造一個 Node 命令行工具的完整過程,涵蓋 bin 目錄、符號鏈接、commander 模塊、命令創建、參數解析與幫助提示。感興趣的朋友不妨動手實踐,只有自己動手做過,才算真正掌握。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved