node-arg-parser
Version:
A simple, chainable command-line argument parser for Node.js CLI tools. Supports type validation, short & long args, and automatic help display.
154 lines (101 loc) β’ 2.66 kB
Markdown
A simple, chainable command-line argument parser for Node.js CLI tools. Supports type validation, short & long args, and automatic help display.
Install via npm:
```bash
npm install node-arg-parser
```
β
Short and long flags (e.g., `-f` and `--file`)
β
Type validation (`String`, `Number`, `Boolean`)
β
Required or optional arguments
β
Built-in `--help` flag support
β
Automatically aligned usage help
## π Getting Started
### Step 1: Import the Parser
```js
import ArgParser from 'node-arg-parser';
// or for CommonJS:
// const ArgParser = require('node-arg-parser');
```
```js
const parser = new ArgParser();
parser
.add('-f', '--file')
.acceptType(String)
.setDescription('The path to the input file')
.required();
parser
.add('-v', '--verbose')
.acceptType(Boolean)
.setDescription('Enable verbose mode');
parser
.add('-n', '--number')
.acceptType(Number)
.setDescription('A numeric input');
```
```js
const args = parser.parse();
console.log(args);
```
```bash
node app.js --file input.txt --verbose true --number 123
```
β
Output:
```json
{
"file": "input.txt",
"verbose": true,
"number": 123
}
```
You donβt need to configure this manually. Just run:
```bash
node app.js --help
```
π§Ύ Output:
```
Usage:
-f --file The path to the input file
-v --verbose Enable verbose mode
-n --number A numeric input
```
Defines a new argument.
- `short`: e.g. `-f`
- `long`: e.g. `--file`
Returns a chainable object.
Defines expected type: `String`, `Number`, or `Boolean`
Sets a human-readable description (used in help output)
### `.required([true|false])`
Marks argument as required (default is `false`)
## π§ͺ Example with Validation
```js
parser
.add('-p', '--port')
.acceptType(Number)
.setDescription('Port to run the server on')
.required();
```
```bash
node app.js --port 3000
node app.js --port abc
```
**Jatin Gohil**
GitHub: [@lkjatinc669](https://github.com/lkjatinc669)
Found a bug or want to contribute? Open an issue or PR at:
π [https://github.com/lkjatinc669/node-arg-parser/issues](https://github.com/lkjatinc669/node-arg-parser/issues)
Licensed under the [ISC License](https://opensource.org/licenses/ISC)