This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Nopt Option Parser Cheatsheet

A quick reference guide for Nopt: npm's option parser for Node.js, type definitions, shorthands, remaining argv handling, and validation.

· Published

nopt is the option parser used internally by npm and many command-line tools.

Basic Usage

const nopt = require('nopt');

// 1. Define expected option types
const knownOpts = {
  foo: [String, null],
  size: ['big', 'medium', 'small'],
  many: [String, Array],
  debug: Boolean,
  version: Boolean,
  help: Boolean
};

// 2. Define short aliases
const shortHands = {
  h: '--help',
  v: '--version',
  d: '--debug'
};

// 3. Parse arguments
const parsed = nopt(knownOpts, shortHands, process.argv, 2);

Output Structure

Given CLI command:

node app.js --size big -d input1.txt input2.txt

The resulting parsed object:

{
  size: 'big',
  debug: true,
  argv: {
    remain: ['input1.txt', 'input2.txt'], // Non-option positional arguments
    cooked: ['--size', 'big', '--debug', 'input1.txt', 'input2.txt'],
    original: ['--size', 'big', '-d', 'input1.txt', 'input2.txt']
  }
}

Supported Types

  • String
  • Boolean
  • Number
  • Array
  • Date
  • path (normalizes path strings)
  • url (validates URL strings)
  • Enums: ['small', 'medium', 'large']

References

Related topics