Command-line arguments
Local practice: Node.js 22.16.0 and npm 10.9.2 on Linux x64; proposed teaching baseline 26.13.1 LTS remains untested. Use a fresh disposable folder for each example, copy only the shown files and run the fixed command. No packages or external services required. Static examples are not ByteMind runner support. The archive is author-only; do not copy expected.json into the example directory.
Collect arguments
import process from "node:process";console.log(JSON.stringify(process.argv.slice(2)));Run in this fixture directory:
node main.mjs 'Pocket Guide' 3Expected stdout:
["Pocket Guide","3"]Expected exit status: 0. Expected stderr: empty. The quoted title is one argument containing a space; the quantity is a string.
How it works
Import process from node:process or use the global process object. process.argv.slice(2) selects user arguments in the file-based examples. Arguments are strings; convert numbers only after defining valid input. Shell quoting determines how words become individual arguments. A command-line tool should define required positions or flags and reject missing or extra input as appropriate. For more complex interfaces a dedicated parser can be useful; keep the first tool simple.
Validate a quantity
import process from "node:process";const [raw] = process.argv.slice(2);if (!/^\d+$/.test(raw ?? "") || Number(raw) > 100) { console.error("Quantity must be 0 through 100"); process.exitCode = 1;} else { console.log(Number(raw) * 250);}Run in this fixture directory:
node main.mjs 2.5Expected stdout: (empty).
Expected exit status: 1. Expected stderr contains Quantity must be 0 through 100. The invalid string is rejected before calculation, and the error is separate from ordinary output.
Common mistake
Do not treat argv[0] as the first user argument or assume "0" is a numeric zero. Do not use shell-sensitive input to construct executable commands.
Try it yourself
Extend the quantity tool to take a second argument for unit price in cents. Reject missing, negative and non-integer values; test zero and the upper bound.
Further reading: Official documentation 1. Related ByteMind reference candidate: node-process-argv (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Command-line arguments — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What is argv.slice(2) for node main.mjs 7?
Why validate before Number conversion?
How is a title with spaces passed as one argument in a shell?