[Tools] Create a Simple CLI Tool in Node.js with CAC
2023-09-14 09:00:49 时间
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 cac to 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:
相关文章
- 【nodejs原理&源码赏析(7)】【译】Node.js中的事件循环,定时器和process.nextTick
- node.js - 定义全局变量
- Node.js进程管理之Process模块
- Node.js其他模块
- [Node.js] Resolve path problem in all envs (require.resolve)
- [Node.js] Gzip + crypto in stream
- [Tools] Convert SVG to a PDF in Node with PDFKit and SVG.js
- [Docker] Build a Simple Node.js Web Server with Docker
- [Node.js] Creating JWTs (JSON Web Tokens) in Node
- [Node.js] Use "prestart" in scripts
- [Node.js] Migration with Umzug
- [Node.js] Add node.js command line to global
- [Node.js] Serve a random static file with Express
- [Node.js] Mock an API for Local Development in React with Mirage JS
- [Node.js] Gzip + crypto in stream
- [WASM] Run WebAssembly in Node.js using the node-loader
- [Node.js] Trigger a File Download in Express
- [Nuxt] Add Arrays of Data to the Vuex Store and Display Them in Vue.js Templates
- [Whole Web, Node.js PM2] Loggin with PM2
- paip.编程语言方法重载实现的原理及python,php,js中实现方法重载
- Node.js Event Loop 处理的几大周期介绍
- Node.js:mysql2.js的基本操作增删改查
- Node.js:使用nrm来管理npm源
- Node.js学习笔记——会话控制