博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Tools] Create a Simple CLI Tool in Node.js with CAC
阅读量:4884 次
发布时间:2019-06-11

本文共 1648 字,大约阅读时间需要 5 分钟。

Command-line tools can help you with all sorts of tasks. This lesson covers the very basics of setting up a CLI tool in Node.js by creating your project with npm, setting up your bin script, and using CAC to parse a single argument.

 

Create a new project, change the "name" porp's value to "hi", then add a "bin" prop, so next time, when we invoke "hi", it will run the command in "bin".

package.json

{  "name": "hi",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC",  "bin": "./index.js",  "devDependencies": {    "cac": "6.3.12"  }}

 

Install:

npm i -D cac

 

Create index.js file:

  • Make sure you have '
    #!/usr/bin/env node
    ' on the top of the file, then it knows should run in node env.
  • Using to build commad, you can define 'option', 'command'
  • Last you should always call cli.parse() to run the command
#!/usr/bin/env nodeconst cli = require('cac')();cli.option('--type 
', 'Provide type, [date|foo]')// name is a required fieldcli.command('
', 'Provide your name') .action((name, options) => { const {type} = options; if (type === 'date') { console.log(`Hi ${name}, Today is ${
new Date().toDateString()}`) } else if (type === 'foo') { console.log(`Hi ${name}, you should take a rest!`) } else { console.log(`Hi ${name}, Good job!`) } })cli.help()// Display version number when `-h` or `--help` appearscli.version('0.0.0')cli.parse()

 

Run:

 

转载于:https://www.cnblogs.com/Answer1215/p/10220555.html

你可能感兴趣的文章
Python 中 global、nonlocal的使用
查看>>
程序员怎么样保证自己的程序没有BUG(zz)
查看>>
两个有序数组合并到一个新数组
查看>>
SPRING IN ACTION 第4版笔记-第九章Securing web applications-003-把用户数据存在数据库
查看>>
Python基础知识:集合
查看>>
Ubuntu搭建Eclipse+JDK+SDK的Android (转载)
查看>>
CSS ie6中双倍margin解决方案
查看>>
C++程序设计方法2:函数运算符重载
查看>>
C++程序设计方法3:对象组合
查看>>
mysql 连接url中useUnicode=true&characterEncoding=UTF-8 的作用
查看>>
带分数 (全排列)
查看>>
第二次作业
查看>>
Cognos集成至portal平台运行报表时只出“#”
查看>>
高级软件测试11.30日小组工作-1701班第5组
查看>>
python第三方模块安装
查看>>
UIApplication和OpenUrl的基于使用方法
查看>>
python 查看某个模块都有什么方法
查看>>
SpringCloud Eureka服务治理机制
查看>>
从vue-cli 到 Vue CLI 3
查看>>
英文读音
查看>>