Sequence NODE_227
MediumParse CLI Arguments into an Object
Node.js
Technical Specification
Build a simple command-line arguments parser that supports flags like --port=3000 --mode=dev.
Input/Output Samples
Input:node app.js --port=3000 --mode=dev
Output:{ port: '3000', mode: 'dev' }
Optimal Logic Path
function parseArgs(argv) {
const args = {};
for (const item of argv.slice(2)) {
if (!item.startsWith("--")) continue;
const [key, value] = item.slice(2).split("=");
args[key] = value ?? true;
}
return args;
}
console.log(parseArgs(process.argv));Architectural Deep-Dive
We manually parse arguments into a dictionary allowing simple config for CLI apps.