使用Node.js開發命令行工具是開發者應該掌握的一項技能,適當編寫命令行工具以提升開發效率。javascript
老規矩第一個程序爲hello world
。在工程中新建bin目錄,在該目錄下建立名爲helper的文件,具體內容以下:html
#!/usr/bin/env node console.log('hello world');
修改helper文件的權限:java
$ chmod 755 ./bin/helper
執行helper文件,終端將會顯示hello world:node
$ ./bin/helper hello world
接下來咱們建立一個符號連接,在全局的node_modules目錄之中,生成一個符號連接,指向模塊的本地目錄,使咱們能夠直接使用helper
命令。
在工程的package.json文件中添加bin字段:git
{ "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
命令:github
$ helper hello world
爲了更高效的編寫命令行工具,咱們使用TJ大神的commander模塊。npm
$ npm install --save commander
helper文件內容修改成:json
#!/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>
命令。
更多的使用方式能夠參考TJ - commander.js文檔。
ruanyifeng
TJ