Skip to main content
Deno 2 is finally here 🎉️
Learn more

Deno Args

GitHub Actions: CI Travis Build Status

Extensible CLI arguments parser for Deno with intelligent TypeScript inference.

Demo and Examples

Demo on YouTube

https://youtu.be/luzgMWrRJxw

Example Code

import args from "https://deno.land/x/args@2.0.0/wrapper.ts";
import {
  EarlyExitFlag,
  Option,
} from "https://deno.land/x/args@2.0.0/flag-types.ts";
import {
  FiniteNumber,
  Choice,
} from "https://deno.land/x/args@2.0.0/value-types.ts";
import {
  PARSE_FAILURE,
} from "https://deno.land/x/args@2.0.0/symbols.ts";

const parser = args
  .describe("Add or subtract two numbers")
  .with(
    EarlyExitFlag("help", {
      describe: "Show help",
      exit() {
        console.log(parser.help());
        return Deno.exit();
      },
    })
  )
  .with(
    Option("a", {
      type: FiniteNumber,
      describe: "Value of a",
    })
  )
  .with(
    Option("b", {
      type: FiniteNumber,
      describe: "Value of b",
    })
  )
  .with(
    Option("operator", {
      type: Choice<"add" | "sub">(
        {
          value: "add",
          describe: "Add two numbers",
        },
        {
          value: "sub",
          describe: "Subtract two numbers",
        }
      ),
      alias: ["o"],
      describe: "Operator to use",
    })
  );

const res = parser.parse(Deno.args);

if (res.tag === PARSE_FAILURE) { // Alternatively, `if (res.error) {`
  console.error("Failed to parse CLI arguments");
  console.error(res.error.toString());
  Deno.exit(1);
} else {
  const { a, b, operator } = res.value;
  switch (operator) {
    case "add":
      console.log(a + b);
      break;
    case "sub":
      console.log(a - b);
      break;
  }
}

Sample Apps

Become a Patron

My Patreon Page.

Development

All tasks are in Drakefile.ts.

Run all tests

deno run -A --unstable Drakefile.ts all

Fix files

env UPDATE=true deno run -A --unstable Drakefile.ts all

License

MIT © Hoàng Văn Khải