Argument Parsing Libraries: minimist
You'll learn how to use minimist to parse command-line arguments effortlessly, handling flags, booleans, and named options without manual string manipulation.
Why minimist?
You've already learned to parse process.argv manually, but that quickly becomes tedious. What if you want to handle --name=John, -v, or --verbose gracefully? minimist is a lightweight library that transforms raw command-line arguments into a friendly JavaScript object.
How It Works
Install minimist first:
npm install minimist
Then use it in your script:
const minimist = require('minimist');
const args = minimist(process.argv.slice(2));
console.log(args);
If you run:
node app.js --name=Alice --verbose -p 3000 file1.txt file2.txt
minimist outputs:
{
_: ['file1.txt', 'file2.txt'],
name: 'Alice',
verbose: true,
p: 3000
}
Understanding the Output
- Named arguments like
--name=Alicebecome properties:args.name - Boolean flags like
--verbosebecometrueautomatically - Short flags like
-p 3000work seamlessly - Non-flagged arguments (positional) go into the
_array
Practical Example
const minimist = require('minimist');
const args = minimist(process.argv.slice(2));
if (args.help) {
console.log('Usage: node app.js --name <name> --port <number>');
process.exit(0);
}
console.log(`Hello, ${args.name || 'stranger'}!`);
console.log(`Port: ${args.port || 8080}`);
Key Takeaway:
minimist transforms messy command-line arguments into a clean object, automatically handling flags (--verbose), named options (--port=3000), and short forms (-p 3000) with zero manual parsing.