[Tools] Create a Simple CLI Tool in Node.js with CAC
2024-08-26 03:16:24
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:
最新文章
- list for循环中删除元素
- Thrift-java学习小结
- string标准库的使用
- Maven第一篇【介绍、安装、结构目录】
- How to use GitHub with Android Studio
- 网站开发进阶(三十七)JSP页面跳转问题解决
- 谈谈 TCP 的 TIME_WAIT
- Windows之系统自带截屏快捷键
- java中级——二叉树比较冒泡和选择排序
- P1914 一串字母
- Saiku免登录嵌入其他系统使用(十一)
- 调试https接口
- golang统计出其中英文字母、空格、数字和其它字符的个数
- mysql 操作sql语句 操作数据库
- Redis等缓存数据库为什么访问会比较快?
- solr之模糊搜索(Fuzzy matching)
- php基础和数据库
- 7. myeclipse10反编译插件安装
- springcloud-eureka简单实现
- UVa 1412 - Fund Management(状压DP + 预处理)
热门文章
- 牛客~~wannafly挑战赛19~A 队列
- Audio Unit 介绍
- oracle的隐式游标
- java 复习整理(二 数据类型和几种变量)
- How to secure remote desktop connections using TLS/SSL
- C++封装随笔
- (九)经典_STM32_ADC多通道采样的例子
- java基础练习 13
- mogilefsdBUG mogilefsd[15624]: crash log: Modification of a read-only value attempted at /usr/local/share/perl5/Sys/Syscall.pm line 227
- C++内联汇编,输出人物名字