Introduction to Subarg
Subarg is a powerful command-line argument parser for JavaScript, offering exceptional flexibility and ease of use. It allows you to parse complex argument structures with nested sub-commands and options.
Basic Usage
To get started with Subarg, you need to install it via npm:
npm install subarg
Here is a basic example of how you might use Subarg to parse command-line arguments:
const subarg = require('subarg');
const argv = subarg(process.argv.slice(2));
console.log(argv);
Subcommand Arguments
Subarg allows you to parse arguments with subcommands:
const argv = subarg(['deploy', '--env', 'production', 'serve', '--port', '8080']);
console.log(argv);
// Output: { _: ['deploy', 'serve'], env: 'production', port: 8080 }
Nested Subcommands
Subarg can handle nested subcommands for more complex CLI applications:
const argv = subarg([
'dev',
'server',
'--env', 'development',
'--',
'client',
'--port', '3000'
]);
console.log(argv);
// Output: { _: ['dev', { _: ['server'], env: 'development', '--': ['client', '--port', '3000'] }] }
Default Values
Subarg allows setting default values for specific options:
const argv = subarg(process.argv.slice(2), { default: { port: 8080 } });
console.log(argv);
// If no port is specified, it defaults to 8080
Boolean Flags
Boolean flags can be easily managed in Subarg:
const argv = subarg(['--verbose', '--force']);
console.log(argv);
// Output: { _: [], verbose: true, force: true }
App Example
Here is a practical example of how Subarg can be used to build a simple CLI tool:
#!/usr/bin/env node
const subarg = require('subarg');
const argv = subarg(process.argv.slice(2));
if (argv.deploy) {
if (argv.env === 'production') {
console.log('Deploying to production server...');
} else if (argv.env === 'staging') {
console.log('Deploying to staging server...');
} else {
console.log('Deploying to development server...');
}
} else if (argv.serve) {
const port = argv.port || 3000;
console.log(`Starting server on port ${port}...`);
} else {
console.log('Unknown command');
}
This script uses Subarg to handle commands and options for deploying and serving applications. Notice how easily Subarg’s API facilitates parsing and handling diverse argument structures.
For more documentation and details, visit the official Subarg GitHub repository.
Hash: 646396ae956009119879bbf51f07130e27c8a0f6973d92e7eb299d92cd97fb03