Chuyển đến nội dung

Bài 9 · Language and Runtime Basics

Command-Line Arguments and Environment Variables

Read command-line arguments with Deno.args and parseArgs, use Deno.env and .env files for configuration, validate settings, set exit codes and build a small CLI tool in Deno.

A program that always does the same thing is rarely useful. Real tools take input: a file name, a flag such as --verbose, a port number, an API key. Deno gives you two main ways to configure a program from outside: command-line arguments and environment variables. This lesson covers both, plus the standard library's argument parser and a safe way to load .env files.

Because Deno is not installed on the site, Deno calls are read-only. Runnable examples use Node.js's util.parseArgs and process.env, which work nearly the same way.

Command-line arguments

Everything after the script name lands in Deno.args, an array of strings:

TypeScript
// args.ts
console.log(Deno.args);
Terminal
deno run args.ts hello --name=Ada -v 3
TEXT
[ "hello", "--name=Ada", "-v", "3" ]

Notice that Deno's own flags (such as --allow-read) go before the script name. Anything after the script name belongs to your program:

Terminal
deno run --allow-read main.ts --allow-read
#         ^ for Deno        ^ for your script

Parsing flags with @std/cli

Parsing --name=Ada by hand is tedious and easy to get wrong. The standard library has parseArgs:

TypeScript
import { parseArgs } from "jsr:@std/cli@1/parse-args";

const args = parseArgs(Deno.args, {
  string: ["name", "greeting"],
  boolean: ["shout", "help"],
  alias: { n: "name", s: "shout", h: "help" },
  default: { greeting: "Hello" },
});

if (args.help) {
  console.log("usage: greet.ts [--name NAME] [--greeting TEXT] [--shout]");
  Deno.exit(0);
}

let message = `${args.greeting}, ${args.name ?? "world"}!`;
if (args.shout) message = message.toUpperCase();
console.log(message);
Terminal
deno run greet.ts -n Ada -s
TEXT
HELLO, ADA!

Anything that is not a flag goes in args._, the array of positional arguments. Declare string and boolean options, so that --name 5 is read as the text "5" and not a number, and so that --shout does not swallow the next word as its value.

Node.js ships a similar function, util.parseArgs. Here it parses a fake argument list so you can see the shape of the result:

Node.js Parsing flags (Node.js stand-in for parseArgs)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exit codes

A command-line tool tells its caller whether it worked through the exit code: 0 means success, anything else means failure. Use Deno.exit(code):

TypeScript
if (Deno.args.length === 0) {
  console.error("error: missing file name");
  Deno.exit(2);
}

Print error messages with console.error so they go to standard error. Deno.exit ends the process immediately, so finish any cleanup first. Setting Deno.exitCode = 1 marks failure but lets the program finish normally.

Environment variables

Environment variables are named strings provided by the operating system. They are the standard way to pass secrets and per-machine settings (API keys, database URLs, a port), because they stay out of source control.

TypeScript
const port = Deno.env.get("PORT"); // string | undefined
Deno.env.set("MODE", "debug");
Deno.env.delete("MODE");
const all = Deno.env.toObject();   // every variable as an object
Terminal
PORT=3000 deno run --allow-env=PORT main.ts

Reading the environment needs --allow-env. Give it a list (--allow-env=PORT,API_KEY) so a dependency cannot read variables you never intended to share. On Windows PowerShell, set a variable with $env:PORT = "3000" before the command.

Deno.env.get always returns a string or undefined, so convert and validate:

Node.js Reading and validating configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read all configuration once at startup into one validated object. That way a typo in a variable name fails loudly at launch, not at 3 a.m. when the code path is first used.

.env files

During development it is convenient to keep variables in a .env file, for example:

TEXT
PORT=3000
API_KEY=dev-key-123

Deno can load it for you:

Terminal
deno run --env-file --allow-env main.ts          # reads .env
deno run --env-file=.env.local main.ts           # a specific file

Or from code with the standard library:

TypeScript
import "jsr:@std/[email protected]/load"; // loads .env into Deno.env

Add .env to .gitignore, and commit a .env.example with fake values so teammates know which variables exist. Variables already set in the real environment normally win over the file.

Here is what a loader does underneath. A simple parser is a good exercise in string handling:

Node.js A minimal .env parser

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Putting it together: a small CLI

TypeScript
import { parseArgs } from "jsr:@std/cli@1/parse-args";

const args = parseArgs(Deno.args, {
  boolean: ["json"],
  string: ["file"],
});

if (!args.file) {
  console.error("usage: wc.ts --file PATH [--json]");
  Deno.exit(2);
}

const text = await Deno.readTextFile(args.file);
const stats = {
  lines: text.split("\n").length,
  words: text.split(/\s+/).filter(Boolean).length,
  bytes: new TextEncoder().encode(text).length,
};

console.log(args.json ? JSON.stringify(stats) : `${stats.lines} lines, ${stats.words} words`);
Terminal
deno run --allow-read=notes.txt wc.ts --file notes.txt --json

Run it with only the permission it needs, and you get a tool that is safe to share. You will build on this in the Projects and Practice chapter of the Deno track.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Where do your program's own arguments go on the command line?

    Flags before the script name belong to Deno; everything after belongs to your program and ends up in Deno.args.
  2. 2. What does Deno.env.get("PORT") return when PORT is not set?

    It returns undefined; it only throws if the permission is missing.
  3. 3. Which flag lets Deno read variables from a .env file?

    --env-file loads .env (or a named file) into the environment before the program starts.
  4. 4. Why should you declare string and boolean options for parseArgs?

    Without types, parseArgs guesses, which can mis-read numbers as numbers and treat a following word as a value.

Summary

  • Deno.args holds the arguments after the script name; Deno's own flags go before it.
  • parseArgs from @std/cli parses flags, aliases and defaults.
  • Exit codes: 0 success, non-zero failure; print errors to stderr.
  • Deno.env reads variables and needs --allow-env, ideally scoped by name.
  • Validate configuration once at startup.
  • --env-file or @std/dotenv loads .env files; never commit real secrets.

Next: ES Modules and URL Imports

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.