Outline
Command line flags are closely related to command line arguments. A couple of the differences are that order doesn't matter with flags, and you can also more easily set default values for flags. You've likely used flags if you've ever used any CLI in the past, and we've seen a few examples in this course so far. The --allow-net
flag is an example. Its default value is false
, but by providing the flag, it's set to true
.
Deno provides a flags module that allows you to parse the Deno.args
object to be able to grab the flags command line flags passed to the script. You can parse the flags like this:
// command-line-flags.ts
const { args } = Deno;
import { parse } from 'https://deno.land/std/flags/mod.ts';
const parsedArgs = parse(args);
console.log(parsedArgs);
With this setup, you can access both command line arguments and command line flags. You can access the arguments like this: parsedArgs['_']
. That's an underscore, if it's hard to tell. Any command line arguments are placed into that array. If none are provided, the array is empty. If you run the above file with an argument and a flag, you'll see the following printed out:
deno run command-line-flags.ts argument --myFlag my-flag-value
{ _: ["argument"], myFlag: "my-flag-value" }
If you don't provide a value for a flag, then its value is the boolean
value true
.
For this assignment, print out a message to a person, passing in their name as a name
command line flag. Set a backup value for the flag in case the flag is forgotten. This is very similar to the command line arguments assignment, but instead you'll be using a flag.