To read command-line arguments passed to a Node.js script, slice off the first two entries of process.argv (process.argv.slice(2)), because process.argv[0] is the node executable path and process.argv[1] is the script file path. You pass arguments on the command line after the script name (for example, node script.js input.txt --verbose), and then parse positional values or --key=value / --flag options from the sliced array.
1. Reading Positional Arguments with process.argv.slice(2)
Always start with const args = process.argv.slice(2); so index 0 corresponds to the first user-supplied argument:
// Run as: node report.js sales-q4.csv 10
const args = process.argv.slice(2);
const [filePath, limitArg] = args;
if (!filePath) {
console.error("Usage: node report.js <filePath> [limit]");
process.exitCode = 1;
} else {
const parsedLimit = limitArg !== undefined ? Number(limitArg) : 25;
console.log("Target file:", filePath);
console.log("Row limit:", Number.isFinite(parsedLimit) ? parsedLimit : 25);
}
process.argv[0]: Path to the Node.js binary (node).process.argv[1]: Path to the executed JavaScript file.process.argv.slice(2): Contains only the arguments passed after the script name, keeping indexing predictable.
2. Parsing Flags and --key=value Options from process.argv
For scripts with flags (like --dry-run) or --key=value / --key value pairs, iterate over process.argv.slice(2) into a structured options object and a positional list:
// Run as: node sync.js users.json --env=staging --limit 50 --dry-run
function parseCliArgs(rawArgs = process.argv.slice(2)) {
const options = {};
const positional = [];
for (let i = 0; i < rawArgs.length; i += 1) {
const token = rawArgs[i];
if (token.startsWith("--") && token.includes("=")) {
const eqIndex = token.indexOf("=");
const key = token.slice(2, eqIndex);
const val = token.slice(eqIndex + 1);
options[key] = val;
} else if (token.startsWith("--")) {
const key = token.slice(2);
const nextToken = rawArgs[i + 1];
if (nextToken !== undefined && !nextToken.startsWith("-")) {
options[key] = nextToken;
i += 1;
} else {
options[key] = true;
}
} else {
positional.push(token);
}
}
return { positional, options };
}
const parsedCli = parseCliArgs(["users.json", "--env=staging", "--limit", "50", "--dry-run"]);
console.log("Parsed CLI:", parsedCli);
- Handles multiple argument styles: Supports positional arguments alongside
--key=value,--key value, and standalone boolean flags like--dry-run. - Node built-in alternative (
node:utilparseArgs): Modern Node.js versions also provideparseArgsfrom"node:util"for stricter flag schemas when needed.
3. Common Traps to Avoid
Reading arguments through process.argv in Node.js commonly runs into a few issues:
- Indexing
process.argv[0]orprocess.argv[1]as user input:argv[0]andargv[1]are executable and script paths—always slice withprocess.argv.slice(2)first. - Treating all
process.argventries as numbers or booleans: Every item inprocess.argvis astring, so"false"is a non-empty truthy string unless explicitly converted and validated. - Forgetting
--when passing flags throughnpm run: Runningnpm run script -- --port=3000passes--port=3000to the underlying Node script, whereas omitting--can pass flags tonpmitself.
TL;DR: Use process.argv.slice(2) to read user-supplied command-line arguments, and convert or parse strings into numbers, booleans, or --key=value options explicitly.
Are you parsing simple positional arguments, --flag / --key=value options, or validating required CLI inputs with exit codes?
