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


    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:

  • 相关阅读:
    FreeRTOS移植到Cortex-M3-M4
    码位颠倒C程序
    开平方与魔数0x5F3759DF:Quake III 开源代码
    MathJax: Web 页面显示数学公式
    Notepad++ NppExport: 让你在Microsoft word 中粘贴语法高亮代码
    [转]matlab 函数三种定义方式
    机器上的几种Eclipse
    自己开发CC3000模块
    Java中的线程的生命周期大体可分为5种状态
    srand和rand的用法和联系
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10220555.html
Copyright © 2020-2023  润新知