Parse command line arguments in Deno

0
1193
Parse command line arguments in Deno
Parse command line arguments in Deno

In this post, we will learn about how to parse command line arguments in Deno.

In Deno, command line arguments are stored into Deno.args object. You can print it out to see them:

// file: main.ts
// print all arguments
console.log(Deno.args)

// print each argument separately
console.log(Deno.args[0]);
console.log(Deno.args[1]);
console.log(Deno.args[2]); // we will not provide this 3rd argument

and execute it:

$ deno run main.ts "Pete Houston" "Parse command line arguments in Deno"

[ "Pete Houston", "Parse command line arguments in Deno" ]
Pete Houston
Parse command line arguments in Deno
undefined

As you can see, the Deno.args is an array and you can access them using index operator []. If the argument is not provided, the value is undefined.

Deno also provides a way to parse arguments as flag options like --name="Pete", --published

This is how it works:

// file: main.ts
// import the parse() function
import { parse } from "https://deno.land/std@0.147.0/flags/mod.ts";

// parse into flag options
const flags = parse(Deno.args, {
    string: ["author", "title"],
    boolean: ["published"],
})

// print each flag option
console.log('author: ' + flags.author);
console.log('title: ' + flags.title);
console.log('published: ' + flags.published);

// print the flags object structure
console.log(flags);

This is the expected output:

$ deno run main.ts --author="Pete Houston" "Parse command line arguments in Deno"
author: Pete Houston
title: undefined
published: false
{
  _: [ "Parse command line arguments in Deno" ],
  author: "Pete Houston",
  published: false
}

Because we want arguments acting with flag options, so if there is any option not provided with a flag, it will not be parsed into a property. For the provided flag options, they can be accessed as properties of the parsed object.

In addition, the flags._ object is an array containing the rest of non-flag arguments.

That’s how you parse command line arguments in Deno.

Have fun!