分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

[Tools] Create a Simple CLI Tool in Node.js with CAC

发布时间:2023-09-06 02:28责任编辑:林大明关键词:jsNode

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 nodeconst cli = require(‘cac‘)();cli.option(‘--type <type>‘, ‘Provide type, [date|foo]‘)// name is a required fieldcli.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` appearscli.version(‘0.0.0‘)cli.parse()

Run:

[Tools] Create a Simple CLI Tool in Node.js with CAC

原文地址:https://www.cnblogs.com/Answer1215/p/10220555.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved