Node.js命令行工具開發

Node.js命令行工具開發

使用Node.js開發命令行工具是開發者應該掌握的一項技能,適當編寫命令行工具以提升開發效率。javascript

hello world

老規矩第一個程序爲hello world。在工程中新建bin目錄,在該目錄下建立名爲helper的文件,具體內容以下:html

#!/usr/bin/env node

console.log('hello world');

修改helper文件的權限:java

$ chmod 755 ./bin/helper

執行helper文件,終端將會顯示hello worldnode

$ ./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

commander模塊

爲了更高效的編寫命令行工具,咱們使用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 -hhelper -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 hellohelper 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文檔。

關鍵知識點

npm link

ruanyifeng

commander.js

TJ

相關文章
相關標籤/搜索