Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
/noptPublic

Node/npm Option Parsing

License

NotificationsYou must be signed in to change notification settings

npm/nopt

Repository files navigation

If you want to write an option parser, and have it be good, there aretwo 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 donethat.

The Right Way is to write some complex configurable program with so manyoptions that you hit the limit of your frustration just trying tomanage them all, and defer it with duct-tape solutions until you seeexactly to the core of the problem, and finally snap and write anawesome 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 servicerestarter, or an operating system. You probably won't end up with agood one of those, but if you don't give up, and you are relentless anddiligent enough in your procrastination, you may just end up with a verynice option parser.

// my-program.jsvarnopt=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 allowedin 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 oflib/nopt.js for more examples ofwhat this puppy can do.

Types

The following types are supported, and defined onnopt.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, andDate is one of the options,then it will return a Date object, not a string.
  • Boolean: Must be eithertrue orfalse. If an option is a boolean,then it does not need a value, and its presence will implytrue asthe value. To negate boolean flags, do--no-whatever or--whatever false
  • NaN: Means that the option is strictly not allowed. Any value willfail.
  • Stream: An object matching the "Stream" class in node. Valuablefor use when validating programmatically. (npm uses this to let yousupply any WriteStream on theoutfd andlogfd config options.)
  • Array: IfArray is specified as one of the types, then the valuewill be parsed as a list of options. This means that multiple valuescan 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 areconsidered 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 beinterpreted as their JavaScript equivalents.

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

To define a new type, add it tonopt.typeDefs. Each item in thathash is an object with atype member and avalidate method. Thetype member is an object that matches what goes in the type list. Thevalidate method is a function that gets called withvalidate(data, key, val). Validate methods should assigndata[key] to the validvalue ofval if it can be handled properly, or return booleanfalse if it cannot.

You can also callnopt.clean(data, types, typeDefs) to clean up aconfig object and remove its invalid properties.

Error Handling

By default nopt logs debug messages ifDEBUG_NOPT orNOPT_DEBUG are set in the environment.

You can assign the following methods tonopt 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 casenext will contain that option.nopt.abbrevHandler(short, long) - Called when an option is automatically translated via abbreviations.

You can also set any of these tofalse 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 --pilnode program.js --no-f --pileofmon# etc.

Shorthands

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

If multiple one-character shorthands are all combined, and thecombination 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 calledargv, 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 appearsin C land, after the v8 and node-specific options have been plucked off.As such,argv[0] is alwaysnode andargv[1] is always theJavaScript program being run.

That's usually not very useful to you. So they're sliced off bydefault. If you want them, then you can pass in0 as the lastargument, or any other number that you'd like to slice off the start ofthe list.


[8]ページ先頭

©2009-2025 Movatter.jp