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 cacto build commad, you can define 'option', 'command'
  • Last you should always call cli.parse() to run the command
#!/usr/bin/env node

const cli = require('cac')();
cli.option('--type <type>', 'Provide type, [date|foo]')
// name is a required field
cli.command('<name>', '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` appears
cli.version('0.0.0')
cli.parse()

Run:

最新文章

  1. list for循环中删除元素
  2. Thrift-java学习小结
  3. string标准库的使用
  4. Maven第一篇【介绍、安装、结构目录】
  5. How to use GitHub with Android Studio
  6. 网站开发进阶(三十七)JSP页面跳转问题解决
  7. 谈谈 TCP 的 TIME_WAIT
  8. Windows之系统自带截屏快捷键
  9. java中级——二叉树比较冒泡和选择排序
  10. P1914 一串字母
  11. Saiku免登录嵌入其他系统使用(十一)
  12. 调试https接口
  13. golang统计出其中英文字母、空格、数字和其它字符的个数
  14. mysql 操作sql语句 操作数据库
  15. Redis等缓存数据库为什么访问会比较快?
  16. solr之模糊搜索(Fuzzy matching)
  17. php基础和数据库
  18. 7. myeclipse10反编译插件安装
  19. springcloud-eureka简单实现
  20. UVa 1412 - Fund Management(状压DP + 预处理)

热门文章

  1. 牛客~~wannafly挑战赛19~A 队列
  2. Audio Unit 介绍
  3. oracle的隐式游标
  4. java 复习整理(二 数据类型和几种变量)
  5. How to secure remote desktop connections using TLS/SSL
  6. C++封装随笔
  7. (九)经典_STM32_ADC多通道采样的例子
  8. java基础练习 13
  9. mogilefsdBUG mogilefsd[15624]: crash log: Modification of a read-only value attempted at /usr/local/share/perl5/Sys/Syscall.pm line 227
  10. C++内联汇编,输出人物名字