nopt vs minimist
Command-Line Argument Parsing in Node.js
noptminimistSimilar Packages:

Command-Line Argument Parsing in Node.js

minimist and nopt are both lightweight libraries for parsing command-line arguments in Node.js applications. They convert process.argv input into structured JavaScript objects, making it easier to handle user-provided flags and options. While both serve the same fundamental purpose, they differ significantly in parsing behavior, configuration capabilities, and design philosophy.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
nopt47,050,12154228.1 kB125 months agoISC
minimist066354.5 kB143 years agoMIT

Command-Line Argument Parsing: minimist vs nopt

Both minimist and nopt solve the same core problem: turning raw command-line strings like --port 8080 --verbose into clean JavaScript objects your code can use. But they take very different approaches to parsing, validation, and usability. Let’s compare them in real-world scenarios.

📥 Input Parsing: How Flags Become Objects

minimist uses intuitive heuristics to infer types and group values.

  • Short flags (-p 8080) and long flags (--port 8080) work out of the box.
  • Repeated flags become arrays automatically.
  • No configuration needed for basic use cases.
// minimist example
const minimist = require('minimist');
const args = minimist(['--port', '8080', '--verbose', '-f', 'input.txt']);
// Result: { _: [], port: 8080, verbose: true, f: 'input.txt' }

nopt requires explicit type definitions but enforces structure.

  • You must declare expected option types upfront.
  • Values are strictly validated against those types.
  • Unknown flags are either ignored or cause errors (depending on config).
// nopt example
const nopt = require('nopt');
const knownOpts = { port: Number, verbose: Boolean, file: String };
const shortHands = { p: ['--port'], v: ['--verbose'], f: ['--file'] };
const args = nopt(knownOpts, shortHands, ['--port', '8080', '--verbose', '-f', 'input.txt']);
// Result: { port: 8080, verbose: true, file: 'input.txt', argv: { ... } }

🔢 Type Handling: Automatic vs Explicit

minimist guesses types based on input format:

  • Numbers stay numbers (--count 55)
  • Booleans for flags without values (--debugtrue)
  • Strings for everything else
// minimist type inference
const args = minimist(['--timeout', '1000', '--dry-run', '--name', 'test']);
// { timeout: 1000, 'dry-run': true, name: 'test' }

nopt requires you to define types explicitly:

  • Only accepts values matching declared types (Number, String, Boolean, Array, etc.)
  • Converts strings to proper types when possible
  • Throws or ignores invalid values based on settings
// nopt strict typing
const opts = { timeout: Number, dryRun: Boolean, name: String };
const args = nopt(opts, {}, ['--timeout', '1000', '--dry-run', '--name', 'test']);
// { timeout: 1000, dryRun: true, name: 'test' }

🧩 Configuration and Defaults

minimist has no built-in support for default values. You handle defaults in your own code:

// minimist defaults (manual)
const argv = minimist(process.argv.slice(2));
const port = argv.port || 3000;
const host = argv.host || 'localhost';

nopt doesn't set defaults either, but its strict typing makes post-parse default assignment cleaner:

// nopt defaults (still manual, but typed)
const parsed = nopt({ port: Number }, {}, process.argv);
const config = {
  port: parsed.port ?? 3000,
  host: parsed.host ?? 'localhost'
};

Note: Neither library provides automatic default value injection — that’s typically handled by higher-level CLI frameworks like yargs or commander.

⚠️ Error Handling and Unknown Flags

minimist never throws errors for unknown flags. Everything unrecognized goes into the _ array:

// minimist ignores unknowns
const args = minimist(['--unknown', 'value', 'file.txt']);
// { _: ['file.txt'], unknown: 'value' }

nopt discards unknown flags by default but can be configured to warn:

// nopt ignores unknowns silently
const args = nopt({ known: String }, {}, ['--unknown', 'flag']);
// { known: undefined } (no 'unknown' property)

Neither provides built-in validation error messages — you’d need to layer that on top.

🛠️ Real-World Usage Patterns

Scenario 1: Simple Dev Tool Script

You’re writing a build script that accepts --watch, --output dir, and source files.

  • Best choice: minimist
  • Why? Minimal setup, automatic boolean/array detection, and unknown args go to _ for file handling.
const args = minimist(process.argv.slice(2));
const { watch, output = 'dist' } = args;
const files = args._; // ['src/index.js', 'src/utils.js']

Scenario 2: Production CLI with Strict Contracts

You’re building a CLI that must reject invalid inputs and enforce types (e.g., --retries must be a number ≥ 0).

  • Best choice: nopt
  • Why? Explicit type definitions prevent silent misinterpretation of values.
const parsed = nopt({ retries: Number }, {}, process.argv);
if (typeof parsed.retries !== 'number' || parsed.retries < 0) {
  throw new Error('--retries must be a non-negative number');
}

📦 Ecosystem and Maintenance

Both packages are mature and stable:

  • minimist is actively maintained with security patches as needed.
  • nopt is maintained by the npm team and used internally by npm itself.

Neither is deprecated, and both remain excellent choices for low-level argument parsing without heavy dependencies.

🆚 Summary: Key Differences

Featureminimistnopt
Type HandlingAutomatic inferenceExplicit declaration required
ConfigurationZero config for basic useRequires type definitions
Unknown FlagsPreserved in _ arraySilently discarded
Default ValuesNot supported (handle manually)Not supported (handle manually)
Error PreventionPermissive (may hide typos)Strict (catches invalid types early)
Best ForSimple scripts, quick prototypesRobust CLIs, type-safe interfaces

💡 Final Recommendation

  • Use minimist when you want "just parse these args" with minimal ceremony. It’s the go-to for small utilities and internal tools where flexibility matters more than strict contracts.

  • Use nopt when you’re building a public-facing CLI that needs to enforce option types and avoid ambiguous interpretations. Its explicit typing prevents subtle bugs in complex argument scenarios.

For most modern projects, consider whether you actually need these low-level parsers — higher-level tools like yargs or commander often provide better DX with built-in help, validation, and subcommands. But when you do need a lean, focused parser, both minimist and nopt deliver reliable, battle-tested solutions.

How to Choose: nopt vs minimist

  • nopt:

    Choose nopt if you require strict type validation, support for default values, and more control over how arguments are interpreted. It's well-suited for larger CLI tools that need robust error handling and consistent option typing, especially when building npm-compatible interfaces.

  • minimist:

    Choose minimist if you need a minimal, zero-dependency parser that handles basic short and long flag syntax with automatic type inference. It's ideal for simple CLIs where you want predictable parsing without complex validation or configuration overhead.

README for nopt

If you want to write an option parser, and have it be good, there are two ways to do it. The Right Way, and the Wrong Way.

The Wrong Way is to sit down and write an option parser. We've all done that.

The Right Way is to write some complex configurable program with so many options that you hit the limit of your frustration just trying to manage them all, and defer it with duct-tape solutions until you see exactly to the core of the problem, and finally snap and write an awesome option parser.

If you want to write an option parser, don't write an option parser. Write a package manager, or a source control system, or a service restarter, or an operating system. You probably won't end up with a good one of those, but if you don't give up, and you are relentless and diligent enough in your procrastination, you may just end up with a very nice option parser.

USAGE

// my-program.js
var nopt = require("nopt")
  , Stream = require("stream").Stream
  , path = require("path")
  , knownOpts = { "foo" : [String, null]
                , "bar" : [Stream, Number]
                , "baz" : path
                , "bloo" : [ "big", "medium", "small" ]
                , "flag" : Boolean
                , "pick" : Boolean
                , "many1" : [String, Array]
                , "many2" : [path, Array]
                }
  , shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
                 , "b7" : ["--bar", "7"]
                 , "m" : ["--bloo", "medium"]
                 , "p" : ["--pick"]
                 , "f" : ["--flag"]
                 }
             // everything is optional.
             // knownOpts and shorthands default to {}
             // arg list defaults to process.argv
             // slice defaults to 2
  , parsed = nopt(knownOpts, shortHands, process.argv, 2)
console.log(parsed)

This would give you support for any of the following:

$ node my-program.js --foo "blerp" --no-flag
{ "foo" : "blerp", "flag" : false }

$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
{ bar: 7, foo: "Mr. Hand", flag: true }

$ node my-program.js --foo "blerp" -f -----p
{ foo: "blerp", flag: true, pick: true }

$ node my-program.js -fp --foofoo
{ foo: "Mr. Foo", flag: true, pick: true }

$ node my-program.js --foofoo -- -fp  # -- stops the flag parsing.
{ foo: "Mr. Foo", argv: { remain: ["-fp"] } }

$ node my-program.js --blatzk -fp # unknown opts are ok.
{ blatzk: true, flag: true, pick: true }

$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value
{ blatzk: 1000, flag: true, pick: true }

$ node my-program.js --no-blatzk -fp # unless they start with "no-"
{ blatzk: false, flag: true, pick: true }

$ node my-program.js --baz b/a/z # known paths are resolved.
{ baz: "/Users/isaacs/b/a/z" }

# if Array is one of the types, then it can take many
# values, and will always be an array.  The other types provided
# specify what types are allowed in the list.

$ node my-program.js --many1 5 --many1 null --many1 foo
{ many1: ["5", "null", "foo"] }

$ node my-program.js --many2 foo --many2 bar
{ many2: ["/path/to/foo", "path/to/bar"] }

Read the tests at the bottom of lib/nopt.js for more examples of what this puppy can do.

Types

The following types are supported, and defined on nopt.typeDefs

  • String: A normal string. No parsing is done.
  • path: A file system path. Gets resolved against cwd if not absolute.
  • url: A url. If it doesn't parse, it isn't accepted.
  • Number: Must be numeric.
  • Date: Must parse as a date. If it does, and Date is one of the options, then it will return a Date object, not a string.
  • Boolean: Must be either true or false. If an option is a boolean, then it does not need a value, and its presence will imply true as the value. To negate boolean flags, do --no-whatever or --whatever false
  • NaN: Means that the option is strictly not allowed. Any value will fail.
  • Stream: An object matching the "Stream" class in node. Valuable for use when validating programmatically. (npm uses this to let you supply any WriteStream on the outfd and logfd config options.)
  • Array: If Array is specified as one of the types, then the value will be parsed as a list of options. This means that multiple values can be specified, and that the value will always be an array.

If a type is an array of values not on this list, then those are considered valid values. For instance, in the example above, the --bloo option can only be one of "big", "medium", or "small", and any other value will be rejected.

When parsing unknown fields, "true", "false", and "null" will be interpreted as their JavaScript equivalents.

You can also mix types and values, or multiple types, in a list. For instance { blah: [Number, null] } would allow a value to be set to either a Number or null. When types are ordered, this implies a preference, and the first type that can be used to properly interpret the value will be used.

To define a new type, add it to nopt.typeDefs. Each item in that hash is an object with a type member and a validate method. The type member is an object that matches what goes in the type list. The validate method is a function that gets called with validate(data, key, val). Validate methods should assign data[key] to the valid value of val if it can be handled properly, or return boolean false if it cannot.

You can also call nopt.clean(data, types, typeDefs) to clean up a config object and remove its invalid properties.

Error Handling

By default nopt logs debug messages if DEBUG_NOPT or NOPT_DEBUG are set in the environment.

You can assign the following methods to nopt for a more granular notification of invalid, unknown, and expanding options:

nopt.invalidHandler(key, value, type, data) - Called when a value is invalid for its option. nopt.unknownHandler(key, next) - Called when an option is found that has no configuration. In certain situations the next option on the command line will be parsed on its own instead of as part of the unknown option. In this case next will contain that option. nopt.abbrevHandler(short, long) - Called when an option is automatically translated via abbreviations.

You can also set any of these to false to disable the debugging messages that they generate.

Abbreviations

Yes, they are supported. If you define options like this:

{ "foolhardyelephants" : Boolean
, "pileofmonkeys" : Boolean }

Then this will work:

node program.js --foolhar --pil
node program.js --no-f --pileofmon
# etc.

Shorthands

Shorthands are a hash of shorter option names to a snippet of args that they expand to.

If multiple one-character shorthands are all combined, and the combination does not unambiguously match any other option or shorthand, then they will be broken up into their constituent parts. For example:

{ "s" : ["--loglevel", "silent"]
, "g" : "--global"
, "f" : "--force"
, "p" : "--parseable"
, "l" : "--long"
}
npm ls -sgflp
# just like doing this:
npm ls --loglevel silent --global --force --long --parseable

The Rest of the args

The config object returned by nopt is given a special member called argv, which is an object with the following fields:

  • remain: The remaining args after all the parsing has occurred.
  • original: The args as they originally appeared.
  • cooked: The args after flags and shorthands are expanded.

Slicing

Node programs are called with more or less the exact argv as it appears in C land, after the v8 and node-specific options have been plucked off. As such, argv[0] is always node and argv[1] is always the JavaScript program being run.

That's usually not very useful to you. So they're sliced off by default. If you want them, then you can pass in 0 as the last argument, or any other number that you'd like to slice off the start of the list.