David's Blog

A Comprehensive Guide to Using Cac in Deno

By David Li on 2023-05-03T14:16:45.022Z

A Comprehensive Guide to Using Cac in Deno

Introduction

Deno is a secure JavaScript and TypeScript runtime built on the V8 JavaScript engine. It’s designed to address some of the shortcomings of Node.js and provide better security and developer experience. One of the powerful features of Deno is its out-of-the-box support for ES Modules, which makes it easier to build modular applications with less boilerplate code.

Cac, short for “Command and Conquer,” is a minimalist CLI (Command Line Interface) framework for building CLI applications. It offers a simple and extensible API inspired by the popular commander.js library, but it’s designed specifically for Deno.

In this article, we’ll discuss how to use Cac in Deno to build a simple command-line application. We’ll cover the following topics:

  1. Installing Deno
  2. Installing Cac
  3. Building a simple CLI application with Cac
  4. Adding commands and options
  5. Handling errors and displaying help messages
  6. Wrapping up

1. Installing Deno

Before we start working with Cac, we need to have Deno installed on our machine. To install Deno, follow the official installation instructions for your specific operating system.

After installing Deno, verify the installation by running the following command:

$ deno --version

This should display the Deno version installed on your machine.

2. Installing Cac

To use Cac in your Deno project, you can import it directly from the official Deno module registry using the following URL:

import { cac } from "https://deno.land/x/cac/mod.ts";

There’s no need to install it using a package manager like npm or yarn.

3. Building a Simple CLI Application with Cac

Let’s create a simple CLI application using Cac. Create a new file called cli.ts and add the following code:

import { cac } from "https://deno.land/x/cac/mod.ts";

const cli = cac();

cli.help(); // Display help message for the CLI

cli.parse(Deno.args);

This code imports the cac function from the Cac module, creates a new CLI instance, displays the help message, and parses the command-line arguments passed to the script.

To run the CLI, execute the following command:

$ deno run cli.ts

This should display the default help message generated by Cac.

4. Adding Commands and Options

Now let’s add some commands and options to our CLI. Modify the cli.ts file as follows:

import { cac } from "https://deno.land/x/cac/mod.ts";

const cli = cac("my-cli");

// Add a command called 'greet' with an optional 'name' argument
cli.command("greet [name]", "Greet a user by name")
  .option("-u, --uppercase", "Greet in uppercase")
  .action((options, name = "stranger") => {
    const greeting = `Hello, ${name}!`;
    console.log(options.uppercase ? greeting.toUpperCase() : greeting);
  });

cli.help(); // Display help message for the CLI

cli.parse(Deno.args);

In this example, we added a new command called greet with an optional name argument and an option -u or --uppercase to greet the user in uppercase. The action function is executed when the command is called, and it receives the parsed options and arguments.

To test the command, run the following:

$ deno run cli.ts greet
$ deno run cli.ts greet John
$ deno run cli.ts greet Jane --uppercase

5. Handling Errors and Displaying Help Messages

Cac automatically generates help messages for your CLI and its commands. However, you can customize these messages or handle errors by using event listeners. Update the cli.ts file as follows:

import { cac } from "https://deno.land/x/cac/mod.ts";

const cli = cac("my-cli");

cli.on("command:*", () => {
  console.error("Invalid command: %s", cli.args.join(" "));
  cli.outputHelp();
  Deno.exit(1);
});

cli.command("greet [name]", "Greet a user by name")
  .option("-u, --uppercase", "Greet in uppercase")
  .action((options, name = "stranger") => {
    const greeting = `Hello, ${name}!`;
    console.log(options.uppercase ? greeting.toUpperCase() : greeting);
  });

cli.help(); // Display help message for the CLI

cli.parse(Deno.args);

In this example, we added an event listener for the command:* event, which is triggered whenan unknown command is entered. The listener logs an error message, displays the help message, and exits the process with a non-zero status code.

Now, if you run an invalid command like this:

$ deno run cli.ts invalid-command

The CLI will display an error message, show the help message, and exit with a non-zero status code.

6. Wrapping Up

In this article, we explored how to use Cac with Deno to build a simple command-line application. We learned how to install and set up Cac, create and parse commands and options, handle errors, and display help messages.

Cac is a powerful and flexible CLI framework that can be easily extended to build more complex CLI applications. You can find more information and examples in the official Cac repository and the Deno module registry.

© Copyright 2024 by FriendlyUsers Tech Blog. Built with ♥ by FriendlyUser. Last updated on 2024-02-29.