前言
Node 給前端開發帶來了很大的改變,促進了前端開發的自動化,我們可以簡化開發工作,然後利用各種工具包生成生產環境。如運行sass src/sass/main.scss dist/css/main.css即可編譯 Sass 文件。
在實際的開發過程中,我們可能會有自己的特定需求,
那麼我們得學會如何創建一個Node命令行工具。
hello world
老規矩第一個程序為hello world。在工程中新建bin目錄,在該目錄下創建名為helper的文件,具體內容如下:
#!/usr/bin/env node
console.log('hello world');
修改helper文件的權限:
$ chmod 755 ./bin/helper
執行helper文件,終端將會顯示hello world:
$ ./bin/helper hello world
符號鏈接
接下來我們創建一個符號鏈接,在全局的node_modules目錄之中,生成一個符號鏈接,指向模塊的本地目錄,使我們可以直接使用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命令:
$ helper hello world
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命令:
$ helper -h Usage: helper [options] Options: -h, --help output usage information -V, --version output the version number $ helper -V 1.0.0
commander模塊提供-h, --help和-V, --version兩個內置命令。
創建命令
創建一個helper hello <author>的命令,當用戶輸入helper hello ipluser時,終端顯示hello ipluser。修改helper文件內容:
#!/usr/bin/env node
var program = require('commander');
program
.version('1.0.0')
.usage('<command> [options]')
.command('hello', 'hello the author') // 添加hello命令
.parse(process.argv);
在bin目錄下新建helper-hello文件:
#!/usr/bin/env node
console.log('hello author');
執行helper hello命令:
$ helper hello ipluser hello author
解析輸入信息
我們希望author是由用戶輸入的,終端應該顯示為hello ipluser。修改helper-hello文件內容,解析用戶輸入信息:
#!/usr/bin/env node
var program = require('commander');
program.parse(process.argv);
const author = program.args[0];
console.log('hello', author);
再執行helper hello ipluser命令:
$ helper hello ipluser hello ipluser
哦耶,終於達到完成了,但作為程序員,這還遠遠不夠。當用戶沒有輸入author時,我們希望終端能提醒用戶輸入信息。
提示信息
在helper-hello文件中添加提示信息:
#!/usr/bin/env node
var program = require('commander');
program.usage('<author>');
// 用戶輸入`helper hello -h`或`helper hello --helper`時,顯示命令使用例子
program.on('--help', function() {
console.log(' Examples:');
console.log(' $ helper hello ipluser');
console.log();
});
program.parse(process.argv);
(program.args.length < 1) && program.help(); // 用戶沒有輸入信息時,調用`help`方法顯示幫助信息
const author = program.args[0];
console.log('hello', author);
執行helper hello或helper hello -h命令,終端將會顯示幫助信息:
$ helper hello Usage: helper-hello <author> Options: -h, --help output usage information Examples: $ helper hello ipluser $ helper hello -h Usage: helper-hello <author> Options: -h, --help output usage information Examples: $ helper hello ipluser
總結
到此我們編寫了一個helper命令行工具,並且具有helper hello <author>命令。剛興趣的朋友們快快自己動手實踐起來,只有自己做了才能算真正的學習了,希望本文對大家能有所幫助。