• Stars
    star
    527
  • Rank 84,091 (Top 2 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Node/npm Option Parsing

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 outputs a warning to standard error when invalid values for known options are found. You can change this behavior by assigning a method to nopt.invalidHandler. This method will be called with the offending nopt.invalidHandler(key, val, types).

If no nopt.invalidHandler is assigned, then it will console.error its whining. If it is assigned to boolean false then the warning is suppressed.

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.

More Repositories

1

npm

This repository is moving to: https://github.com/npm/cli
17,473
star
2

cli

the package manager for JavaScript
JavaScript
8,303
star
3

node-semver

The semver parser for node (the one npm uses)
JavaScript
4,772
star
4

npm-expansions

Send us a pull request by editing expansions.txt
JavaScript
2,209
star
5

tink

a dependency unwinder for javascript
JavaScript
2,153
star
6

ini

An ini parser/serializer in JavaScript
JavaScript
733
star
7

npx

npm package executor
JavaScript
731
star
8

rfcs

Public change requests/proposals & ideation
JavaScript
726
star
9

npm-registry-couchapp

couchapp bits of registry.npmjs.org
JavaScript
615
star
10

registry

npm registry documentation
449
star
11

npmlog

The logger that npm uses
JavaScript
423
star
12

marky-markdown

npm's markdown parser
JavaScript
405
star
13

arborist

npm's tree doctor
JavaScript
369
star
14

documentation

Documentation for the npm registry, website, and command-line interface.
MDX
369
star
15

pacote

npm fetcher
JavaScript
349
star
16

download-counts

Background jobs and a minimal service for collecting and delivering download counts
JavaScript
328
star
17

gauge

A terminal based horizontal guage aka, a progress bar
JavaScript
319
star
18

node-which

Like which(1) unix command. Find the first instance of an executable in the PATH.
JavaScript
305
star
19

init-package-json

A node module to get your node module started
JavaScript
284
star
20

validate-npm-package-name

Is the given string an acceptable npm package name?
JavaScript
282
star
21

cacache

npm's content-addressable cache
JavaScript
274
star
22

npm-merge-driver

git merge driver for resolving conflicts in npm-related files
JavaScript
271
star
23

npm-registry-client

JavaScript
264
star
24

lockfile

A very polite lock file utility, which endeavors to not litter, and to wait patiently for others.
JavaScript
259
star
25

registry-issue-archive

An archive of the old npm registry issue tracker
250
star
26

write-file-atomic

Write files in an atomic fashion w/configurable ownership
JavaScript
217
star
27

read-package-json

The thing npm uses to read package.json files with semantics and defaults and validation and stuff
JavaScript
214
star
28

roadmap

Public roadmap for npm
213
star
29

hosted-git-info

Provides metadata and conversions from repository urls for Github, Bitbucket and Gitlab
JavaScript
206
star
30

fstream

Advanced FS Streaming for Node
JavaScript
205
star
31

make-fetch-happen

making fetch happen for npm
JavaScript
190
star
32

read

read(1) for node.
JavaScript
187
star
33

normalize-package-data

normalizes package metadata, typically found in package.json file.
JavaScript
184
star
34

ndm

ndm allows you to deploy OS-specific service-wrappers directly from npm-packages.
JavaScript
181
star
35

are-we-there-yet

Track complex hiearchies of asynchronous task completion statuses.
JavaScript
173
star
36

abbrev-js

Like ruby's Abbrev module
JavaScript
158
star
37

statusboard

Public monitor/status/health board for @npm/cli-team's maintained projects
JavaScript
152
star
38

security-holder

An npm package that holds a spot.
145
star
39

osenv

Look up environment settings specific to different operating systems.
JavaScript
137
star
40

feedback

Public feedback discussions for npm
133
star
41

npm-registry-fetch

like fetch() but for the npm registry
JavaScript
130
star
42

npm-package-arg

Parse the things that can be arguments to `npm install`
JavaScript
116
star
43

libnpm

programmatic npm API
JavaScript
113
star
44

npm-collection-staff-picks

JavaScript
112
star
45

npm-packlist

Walk through a folder and figure out what goes in an npm package
JavaScript
110
star
46

promzard

A prompting json thingie
JavaScript
101
star
47

npm-remote-ls

Examine a package's dependency graph before you install it
JavaScript
89
star
48

npmconf

npm config thing
JavaScript
75
star
49

cmd-shim

The cmd-shim used in npm
JavaScript
75
star
50

npm-tips

A collection of short (5 words or so) tips and tricks that can be sprinkled about the npm site.
JavaScript
73
star
51

www

community space for the npm website
68
star
52

policies

Privacy policy, code of conduct, license, and other npm legal stuff
Shell
67
star
53

package-json

Programmatic API to update package.json
JavaScript
65
star
54

git

a util for spawning git from npm CLI contexts
JavaScript
62
star
55

npm_conf

A conference about npm, maybe. Not to be confused with npmconf.
59
star
56

ignore-walk

Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.
JavaScript
57
star
57

registry-follower-tutorial

write you a registry follower for great good
JavaScript
56
star
58

ssri

subresource integrity for npm
JavaScript
55
star
59

minipass-fetch

An implementation of window.fetch in Node.js using Minipass streams
JavaScript
54
star
60

ci-detect

Detect what kind of CI environment the program is in
JavaScript
53
star
61

run-script

Run a lifecycle script for a package (descendant of npm-lifecycle)
JavaScript
53
star
62

read-installed

Read all the installed packages in a folder, and return a tree structure with all the data.
JavaScript
52
star
63

mute-stream

Bytes go in, but they don't come out (when muted).
JavaScript
49
star
64

fs-write-stream-atomic

Like `fs.createWriteStream(...)`, but atomic.
JavaScript
48
star
65

read-package-json-fast

Like read-package-json, but faster
JavaScript
48
star
66

libnpmpublish

programmatically publish and unpublish npm packages
JavaScript
46
star
67

logical-tree

Calculates a nested logical tree using a package.json and a package lock.
JavaScript
44
star
68

read-package-tree

Read the contents of node_modules
JavaScript
42
star
69

jobs

41
star
70

unique-filename

Generate a unique filename for use in temporary directories or caches.
JavaScript
40
star
71

lock-verify

Report if your package.json is out of sync with your package-lock.json
JavaScript
38
star
72

fstream-ignore

JavaScript
37
star
73

benchmarks

The npm CLI's benchmark suite
JavaScript
36
star
74

npm-lifecycle

npm lifecycle script runner
JavaScript
36
star
75

wombat-cli

The wombat cli tool.
JavaScript
35
star
76

npme-installer

npm Enterprise installer
JavaScript
35
star
77

couch-login

A module for doing logged-in requests against a couchdb server
JavaScript
33
star
78

libnpmexec

npm exec (npx) Programmatic API
JavaScript
33
star
79

npm-audit-report

npm audit security report
JavaScript
33
star
80

ansible-nagios

Ansible role for building Nagios 4.
Perl
32
star
81

config

Configuration management for https://github.com/npm/cli
JavaScript
32
star
82

parse-conflict-json

Parse a JSON string that has git merge conflicts, resolving if possible
JavaScript
32
star
83

npm-profile

Make changes to your npmjs.com profile via cli or library
JavaScript
31
star
84

unique-slug

Generate a unique character string suitible for use in files and URLs.
JavaScript
31
star
85

fstream-npm

fstream class for creating npm packages
JavaScript
30
star
86

redsess

Yet another redis session thing for node.
JavaScript
30
star
87

concurrent-couch-follower

a couch follower wrapper that you can use to be sure you don't miss any documents even if you process them asynchronously.
JavaScript
28
star
88

npm-registry-mock

mock the npm registry
JavaScript
27
star
89

lint

lint the npmcli way
JavaScript
26
star
90

fs

filesystem helper functions, wrappers, and promisification for the npm cli
JavaScript
25
star
91

template-oss

a template package for npm CLI team development
JavaScript
25
star
92

libnpmsearch

programmatic API for the shiny new npm search endpoint
JavaScript
25
star
93

bin-links

.bin/ script linker
JavaScript
24
star
94

libnpmaccess

programmatic api for `npm access`
JavaScript
24
star
95

logos

official logos for npm, Inc
22
star
96

types

Typescript definitions for npm registry content
JavaScript
22
star
97

public-api

21
star
98

deprecate-holder

An npm package that holds a spot.
21
star
99

map-workspaces

Retrieves a name:pathname Map for a given workspaces config
JavaScript
20
star
100

libnpmversion

library to do the things that 'npm version' does
JavaScript
20
star