0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Deno.args to Access Command Line Arguments

Use Deno.args to access command line arguments passed to a Deno script as an array of strings. Each element in Deno.args represents one argument, starting from the first argument after the script name.
๐Ÿ“

Syntax

Deno.args is a built-in readonly array that contains all command line arguments passed to your Deno script. It does not include the script name itself.

Each element is a string representing one argument.

typescript
const args = Deno.args;
console.log(args);
Output
[]
๐Ÿ’ป

Example

This example shows how to read and print command line arguments using Deno.args. Run the script with arguments to see them listed.

typescript
const args = Deno.args;
if (args.length === 0) {
  console.log("No arguments provided.");
} else {
  console.log("Arguments received:");
  args.forEach((arg, index) => {
    console.log(`${index + 1}: ${arg}`);
  });
}
Output
Arguments received: 1: hello 2: world
โš ๏ธ

Common Pitfalls

  • Expecting Deno.args to include the script name; it does not.
  • Not converting argument strings to the needed type (e.g., number) before use.
  • Assuming arguments are always present without checking Deno.args.length.
typescript
/* Wrong way: */
const firstArg = Deno.args[0];
const numberValue = firstArg + 10; // This concatenates strings, does not add numbers

/* Right way: */
const firstArgNum = Number(Deno.args[0]);
if (!isNaN(firstArgNum)) {
  const sum = firstArgNum + 10;
  console.log(sum);
} else {
  console.log("First argument is not a number.");
}
๐Ÿ“Š

Quick Reference

Summary tips for using Deno.args:

  • Access arguments: Use Deno.args as an array of strings.
  • Check length: Always verify Deno.args.length before using arguments.
  • Convert types: Convert strings to numbers or booleans as needed.
  • Order matters: Arguments are in the order they appear in the command line.
โœ…

Key Takeaways

Use Deno.args to get command line arguments as an array of strings.
Always check if arguments exist before accessing them to avoid errors.
Convert argument strings to the correct type before using them in calculations.
Deno.args does not include the script name; it only contains the arguments.
Arguments are ordered exactly as passed in the command line.