加载中...

八、子命令


yargs 模块还允许通过 command 方法,设置 Git 风格的子命令。

  1. #!/usr/bin/env node
  2. var argv = require('yargs')
  3. .command("morning", "good morning", function (yargs) {
  4. console.log("Good Morning");
  5. })
  6. .command("evening", "good evening", function (yargs) {
  7. console.log("Good Evening");
  8. })
  9. .argv;
  10. console.log('hello ', argv.n);

用法如下。

  1. $ hello morning -n tom
  2. Good Morning
  3. hello tom

可以将这个功能与 shellojs 模块结合起来。

  1. #!/usr/bin/env node
  2. require('shelljs/global');
  3. var argv = require('yargs')
  4. .command("morning", "good morning", function (yargs) {
  5. echo("Good Morning");
  6. })
  7. .command("evening", "good evening", function (yargs) {
  8. echo("Good Evening");
  9. })
  10. .argv;
  11. console.log('hello ', argv.n);

每个子命令往往有自己的参数,这时就需要在回调函数中单独指定。回调函数中,要先用 reset 方法重置 yargs 对象。

  1. #!/usr/bin/env node
  2. require('shelljs/global');
  3. var argv = require('yargs')
  4. .command("morning", "good morning", function (yargs) {
  5. echo("Good Morning");
  6. var argv = yargs.reset()
  7. .option("m", {
  8. alias: "message",
  9. description: "provide any sentence"
  10. })
  11. .help("h")
  12. .alias("h", "help")
  13. .argv;
  14. echo(argv.m);
  15. })
  16. .argv;

用法如下。

  1. $ hello morning -m "Are you hungry?"
  2. Good Morning
  3. Are you hungry?

还没有评论.