Enhance Your CLI Experience with Yargs Parser A Comprehensive Guide

Introduction to yargs-parser

yargs-parser is a powerful library for parsing command-line arguments in Node.js. It aims to provide a simple and user-friendly way to handle input in CLI applications, allowing developers to focus on their core logic instead of argument parsing.

Basic Usage

Let’s look at a simple example of using yargs-parser:


  const yargsParser = require('yargs-parser');
  
  const argv = yargsParser(process.argv.slice(2));
  console.log(argv);

This will parse the command-line arguments and print them as an object.

Advanced Parsing

The library offers various options for advanced parsing:

Alias


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

Default Values


  const argv = yargsParser(process.argv.slice(2), {
    default: {
      port: 3000
    }
  });
  console.log(argv);

Boolean Values


  const argv = yargsParser(process.argv.slice(2), {
    boolean: ['debug']
  });
  console.log(argv);

Coercion


  const argv = yargsParser(process.argv.slice(2), {
    coerce: {
      file: arg => path.resolve(arg)
    }
  });
  console.log(argv);

App Example

Here is a comprehensive example that demonstrates a complete CLI application using yargs-parser:


  const yargsParser = require('yargs-parser');
  const fs = require('fs');

  const argv = yargsParser(process.argv.slice(2), {
    alias: {
      h: 'help',
      v: 'version',
      f: 'file'
    },
    default: {
      file: 'default.txt',
      encoding: 'utf8'
    },
    boolean: ['help', 'version'],
    configuration: {
      'camel-case-expansion': true,
      'short-option-groups': true,
      'dot-notation': true
    },
    coerce: {
      file: arg => path.resolve(arg)
    }
  });

  if (argv.help) {
    console.log('Usage: node app.js --file [filename]');
  } else if (argv.version) {
    console.log('App version 1.0.0');
  } else {
    const filePath = argv.file;
    fs.readFile(filePath, argv.encoding, (err, data) => {
      if (err) {
        console.error(`Error reading file ${filePath}: `, err);
      } else {
        console.log(data);
      }
    });
  }

This example reads a file specified by the --file argument and prints its contents to the console. It supports aliases and default values, and includes help and version options.

By using yargs-parser, developers can quickly build robust and user-friendly CLI applications with minimal effort.


Hash: 797c6489f9729771238b2945c9547adf3011f0b79b2a9ef9dea4e8250477906e

Leave a Reply

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