Comprehensive Guide to Minimist in Node.js for Command Line Argument Parsing

Introduction to Minimst

Minimist is a lightweight library used to parse command line arguments in Node.js. It provides an easy-to-use API to handle flags and options, making it a handy tool for building command line applications.

Useful APIs of Minimist

Below are some of the most useful APIs in the minimist library:

Basic Usage

  const minimist = require('minimist');
  const args = minimist(process.argv.slice(2));
  console.log(args);

This code snippet will parse command line arguments and convert them into a JavaScript object. For example:

  // Command: node app.js --name John --age 30
  // Output: { _: [], name: 'John', age: 30 }

Default Values

  const args = minimist(process.argv.slice(2), { default: { name: 'Guest', age: 25 } });
  console.log(args);

This sets default values for arguments that are not provided:

  // Command: node app.js
  // Output: { _: [], name: 'Guest', age: 25 }

Boolean Arguments

  const args = minimist(process.argv.slice(2), { boolean: ['v', 'h'] });
  console.log(args);

Flags such as -v or -h will be treated as boolean values:

  // Command: node app.js -v
  // Output: { _: [], v: true, h: false }

Alias Arguments

  const args = minimist(process.argv.slice(2), { alias: { v: 'version', h: 'help' } });
  console.log(args);

You can create aliases for arguments for easier use:

  // Command: node app.js --version
  // Output: { _: [], version: true, v: true, help: false, h: false }

Parsing and Grouping Arguments

  const args = minimist(process.argv.slice(2), {
    string: 'env',
    unknown: (arg) => { return false; }
  });
  console.log(args);

This ensures that unknown arguments will be ignored:

  // Command: node app.js --env production --unknown
  // Output: { _: [], env: 'production' }

Example Application

Below is an example of a simple Node.js application using minimist to handle command line arguments:

  const minimist = require('minimist');

  const args = minimist(process.argv.slice(2), {
    default: { name: 'User', age: 20 },
    alias: { n: 'name', a: 'age', h: 'help' },
    boolean: ['h']
  });

  if (args.help) {
    console.log('Usage: node app.js --name [string] --age [num]');
    process.exit(0);
  }

  console.log(`Hello ${args.name}, you are ${args.age} years old.`);

This application provides a help flag, default values, and aliases for name and age arguments:

  // Command: node app.js --name Alice
  // Output: Hello Alice, you are 20 years old.

If the –help flag is provided, it will display usage instructions:

  // Command: node app.js --help
  // Output: Usage: node app.js --name [string] --age [num]

By utilizing the minimist library, you can easily build comprehensive and user-friendly command line applications in Node.js.

Hash: c4414a0eb048df0315ce103eda11d63f80892666da610f41f63cbef084e3c53b

Leave a Reply

Your email address will not be published. Required fields are marked *