Yargs command with positional argument


This post goes over how to add a yargs command with positional arguments.

Prerequisites

Install yargs:

npm install yargs

Create script index.js and import yargs:

const { hideBin } = require('yargs/helpers');
const yargs = require('yargs/yargs');

Command

To have the command accept a positional argument:

const argv = yargs(hideBin(process.argv))
  .command('<argument>', 'Positional argument')
  .parseSync();

To make the command required and not optional:

const argv = yargs(hideBin(process.argv))
  .command('<argument>', 'Positional argument')
  .demandCommand(1)
  .parseSync();

To print out the 1st positional argument:

console.log(argv._[0]);

Code

Here’s the full code:

// index.js
const { hideBin } = require('yargs/helpers');
const yargs = require('yargs/yargs');

const argv = yargs(hideBin(process.argv))
  .command('<argument>', 'Positional argument')
  .demandCommand(1)
  .parseSync();

console.log('1st positional argument:', argv._[0]);

Demo

Replit:



Please support this site and join our Discord!