Introduction to nopt
nopt is a powerful and flexible command-line argument parser for Node.js applications. It allows you to easily define expected options, handle input arguments, and provide informative help messages. With its robust features, nopt is essential for building user-friendly CLI applications.
Setting Up nopt
npm install nopt
Basic Usage
To start using nopt, import the module and define the options you want to handle.
const nopt = require('nopt'); const knownOpts = { "help": Boolean, "version": Boolean, "config": String, "verbose": Boolean, }; const shortHands = { "h": ["--help"], "v": ["--version"], "c": ["--config"], "vv": ["--verbose"] }; const parsed = nopt(knownOpts, shortHands, process.argv, 2);
Advanced Features of nopt
Default Values
const defaults = { verbose: false, config: 'default-config.json' }; const options = nopt(knownOpts, shortHands, process.argv, 2, defaults);
Custom Type Handlers
const url = require('url'); function urlHandler(input) { return url.parse(input); } const knownOpts = { "endpoint": urlHandler, "requestTimeout": Number }; const options = nopt(knownOpts, {}, process.argv, 2);
Mixing Argument Types
const options = nopt({ "log-level": ["info", "warn", "error"], "port": [null, Number] }, { "l": "--log-level", "p": "--port" });
Building a CLI Application with nopt
Below is an example of a CLI application that uses nopt to handle various command-line options.
// cli-app.js const nopt = require('nopt'); const knownOpts = { "help": Boolean, "version": Boolean, "config": String, "verbose": Boolean, "port": Number }; const shortHands = { "h": ["--help"], "v": ["--version"], "c": ["--config"], "vv": ["--verbose"], "p": ["--port"] }; const parsed = nopt(knownOpts, shortHands, process.argv, 2); if (parsed.help) { console.log("Help: Use this CLI app with the following options..."); process.exit(0); } if (parsed.version) { console.log("Version: 1.0.0"); process.exit(0); } if (parsed.config) { console.log(`Loading config file: ${parsed.config}`); // Load configuration logic } if (parsed.verbose) { console.log("Verbose mode is ON"); } console.log(`Server running on port: ${parsed.port || 8080}`);
Conclusion
nopt is a versatile and powerful tool for Node.js developers. Its ability to handle various argument types, provide default values, and integrate custom logic makes it an excellent choice for building robust CLI applications. Start leveraging the capabilities of nopt in your next Node.js project and enhance your command-line interfaces effortlessly.
Hash: 0e7ce202a69218fa110f7d0f9cfe6d137fba295ebb6e740ef79b2ff8947d8c74