Typorithm · easy

argv & env

node-process-argv-envnodejsargvenvparse-args
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn argv & env

0%

CLI & Process

process.argv is the argument array: index 0 is node, index 1 is the script, and slice(2) is the real user arguments. process.env reads configuration as strings. For structured flag parsing, Node's built-in util.parseArgs beats hand-rolled string splitting.

process.argv is an array where argv[0] is the node executable, argv[1] is the path to your script, and everything from index 2 on is the arguments the user typed — so process.argv.slice(2) gives you just those.

process.env is an object of environment variables (always strings), the idiomatic way to inject configuration like PORT or NODE_ENV; pair it with ?? to supply a default when a variable is missing.

Rather than splitting argv by hand, Node ships util.parseArgs, which turns flags like --port 3000 into a structured { values } object with declared types, replacing third-party libraries for simple CLIs.

01

argv[0] = node, argv[1] = script, slice(2) = user args.

02

process.env holds string config like PORT and NODE_ENV.

03

util.parseArgs gives structured flag parsing, no library.

// node app.js --port 3000 hello
process.argv[0]  // "/usr/bin/node"  — the runtime
process.argv[1]  // "/path/app.js"   — the script
process.argv.slice(2)  // ["--port", "3000", "hello"]
const port = process.env.PORT ?? "3000"
const { values } = util.parseArgs({ options: { port: { type: "string" } } })

Read the implementation

Connect each part of the code to the concept before you type.

1. argv[0] is node

process.argv[0] is always the path to the node executable that launched the script.

process.argv[0]  // "/usr/bin/node"  — the runtime

2. argv[1] is the script

process.argv[1] is the full path of the script file being run.

process.argv[1]  // "/path/app.js"   — the script

3. User args

Everything from index 2 onward is the actual user-supplied arguments, so slice(2) gives just those.

process.argv.slice(2)  // ["--port", "3000", "hello"]

4. Read config from env

process.env exposes environment variables as strings; ?? supplies a default when PORT is unset.

const port = process.env.PORT ?? "3000"

5. Structured parsing

util.parseArgs is Node's built-in flag parser that returns structured values instead of a raw array.

util.parseArgs({ options: { port: { type: "string" } } })

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

argv & env: Lesson & Practice · Typorithm | ApplyDjinn