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

相关文章
相关标签/搜索