Hand Rolled CLI Flag Parsing Without Dependencies
Splitting argv into booleans flags, --key=value pairs and positionals, with -- ending option parsing, covers most CLIs before reaching for a parser library.
Code
// Split argv into flags, --key=value pairs, and positionals; -- ends option parsing.
function parseArgs(argv) {
const flags = new Set();
const values = new Map();
const positionals = [];
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--") {
// everything after -- is positional by definition
positionals.push(...argv.slice(i + 1));
break;
}
if (arg.startsWith("--")) {
const eq = arg.indexOf("=");
if (eq !== -1) {
values.set(arg.slice(2, eq), arg.slice(eq + 1));
} else {
flags.add(arg.slice(2));
}
} else {
positionals.push(arg);
}
}
return { flags, values, positionals };
}
const parsed = parseArgs(["deploy", "--env=prod", "--dry-run", "--", "extra", "args"]);
console.log("flags:", [...parsed.flags]);
console.log("values:", [...parsed.values]);
console.log("positionals:", parsed.positionals);Output
Captured from a sandboxed run of this snippet in the build pipeline.
flags: [ 'dry-run' ]
values: [ [ 'env', 'prod' ] ]
positionals: [ 'deploy', 'extra', 'args' ]What the code does
Count the function parseArgs as the entire surface area of Hand Rolled CLI Flag Parsing Without Dependencies.
Iteration happens inside for (let i = 0; i < argv.length; i++) — everything outside it runs once.
The result comes back as an object carrying flags, values.
Applying it
The signature you will call most reads function parseArgs(argv)
Look for the flags:, values:, positionals: prefixes as the file executes; they connect every printed line to the step behind it.
The call returns flags, values — destructure what you need at the call site.
Statements that matter
return { flags, values, positionals };
const values = new Map();
const flags = new Set();
Interactive Tools for This Topic
FAQ
- Does `parseArgs` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `parseArgs` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.