Node.js

NodeJs Shell(上)

2016-10-14  本文已影响751人  卖梦想的男孩

1. 简单脚本

#!/usr/bin/env node
console.log('hi,kerison');
chmod 755 gk
hi,kerison
{
  "name": "gk",
  "bin": {
    "gk": "gk"
  }
}

2. 脚本扩展一(获取命令行的参数)

脚本中的命令参数可以从process.argv中存取

console.log('gk', process.argv)
gk [ '/Users/kerison/.nvm/versions/node/v5.11.1/bin/node',
  '/Users/kerison/.nvm/versions/node/v5.11.1/bin/gk',
  'hello' ]

分析:可以看出process.argv是一个命令的数组,第一个是node命令,第二个是当前程序,后续的是依次传入的参数

npm install --save yargs
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('gk ', argv);
gk { _: [ 'other' ], n: 'x', name: 'kerison', '$0': 'gk' }
#!/usr/bin/env node
var argv = require('yargs')
.option('v', {
    alias: 'version',
    demand: true,
    default: '0.0.1',
    describe: 'version name',
    type: 'string'
})
.option('h', {
    alias: 'help',
    demand: true,
    describe: 'need help',
})
.argv;
console.log('gk ', argv);
选项:
  -v, --version  version name                  [字符串] [必需] [默认值: "0.0.1"]
  -h, --help     need help                                                [必需]
缺少必须的选项:h
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: gk [options]')
   .example('gk -v ', 'somthing')
   .help('h')
   .epilog('copyright 2016')
.argv;
Usage: gk [options]
选项:
  -h  显示帮助信息                                                        [布尔]
示例:
  gk -v   somthing
copyright 2016
#!/usr/bin/env node
var argv = require('yargs')
.command("sub", "sub description ", function(yargs) {
    console.log("sub ...");
})
.usage('Usage: gk [options]')
.example('gk -v ', 'somthing')
.help('h')
.epilog('copyright 2016')
.argv;
Usage: gk [options]
命令:
  sub  sub description
选项:
  -h  显示帮助信息                                                        [布尔]
示例:
  gk -v   somthing
copyright 2016
上一篇下一篇

猜你喜欢

热点阅读