@gerhobbelt/nomnom

中文文档
1.8.4-31发布于 2021/02/04MITCommonJS近 30 天下载 4.3万

Option parser with generated usage and commands

原始使用文档

deprecation notice for original

The original author's nomnom is deprecated; this fork is not: we continue to update this library.

When you are unsure about using this library's fork (or others), you may wish to check out https://github.com/tj/commander.js.

Personally, I prefer using nomnom over commander or other option parsers, so I will keep this one. :-)

nomnom

build status

nomnom is an option parser for node. It noms your args and gives them back to you in a hash.

var opts = require("@gerhobbelt/nomnom")
   .option('debug', {
      abbr: 'd',
      flag: true,
      help: 'Print debugging info'
   })
   .option('config', {
      abbr: 'c',
      default: 'config.json',
      help: 'JSON file with tests to run'
   })
   .option('version', {
      flag: true,
      help: 'print version and exit',
      callback: function() {
         return "version 1.2.4";
      }
   })
   .parse();

if (opts.debug)
   // do stuff

You don't have to specify anything if you don't want to:

var opts = require("@gerhobbelt/nomnom").parse();

var url = opts[0];     // get the first positional arg
var file = opts.file   // see if --file was specified
var verbose = opts.v   // see if -v was specified
var extras = opts._    // get an array of the unmatched, positional args

Install

for node.js and npm:

npm install @gerhobbelt/nomnom

More Details

Nomnom supports args like -d, --debug, --no-debug, --file=test.txt, --file test.txt, -f test.txt, -xvf, and positionals. Positionals are arguments that don't fit the -a or --atomic format and aren't attached to an option.

Values are JSON parsed, so --debug=true --count=3 --file=log.txt would give you:

{
   "debug": true,
   "count": 3,
   "file": "log.txt"
}

Commands

Nomnom supports command-based interfaces (e.g. with git: git add -p and git rebase -i where add and rebase are the commands):

var parser = require("@gerhobbelt/nomnom");

parser.command('browser')
   .callback(function(opts, command) {
      runBrowser(opts.url);
   })
   .help("run browser tests");

parser.command('sanity')
   .option('outfile', {
      abbr: 'o',
      help: "file to write results to"
   })
   .option('config', {
      abbr: 'c',
      default: 'config.json',
      help: "json manifest of tests to run"
   })
   .callback(function(opts, command) {
      runSanity(opts.filename);
   })
   .help("run the sanity tests")

parser.parse();

Each command generates its own usage message when -h or --help is specified with the command.

Usage

Nomnom prints out a usage message if --help or -h is an argument. If no commands are called (the script is simply run without arguments), -h will be called automatically unless you've disabled this feature using the .autoShowUsage(false) API call.

Usage for these options in test.js:

var opts = require("@gerhobbelt/nomnom")
   .script("runtests")
   .options({
      path: {
         position: 0,
         help: "Test file to run",
         list: true
      },
      config: {
         abbr: 'c',
         metavar: 'FILE',
         help: "Config file with tests to run"
      },
      debug: {
         abbr: 'd',
         flag: true,
         help: "Print debugging info"
      }
   }).parse();

...would look like this:

usage: runtests <path>... [options]

path     Test file to run

options:
   -c FILE, --config FILE   Config file with tests to run
   -d, --debug              Print debugging info

Options

You can either add a specification for an option with nomnom.option('name', spec) or pass the specifications to nomnom.options() as a hash keyed on option name. Each option specification can have the following fields:

abbr and full

abbr is the single character string to match to this option, full is the full-length string (defaults to the name of the option).

This option matches -d and --debug on the command line:

nomnom.option('debug', {
   abbr: 'd'
})

This option matches -n 3, --num-lines 12 on the command line:

nomnom.option('numLines', {
   abbr: 'n',
   full: 'num-lines'
})

flag

If this is set to true, the option acts as a flag and doesn't swallow the next value on the command line. Default is false, so normally if you had a command line --config test.js, config would get a value of test.js in the options hash. Whereas if you specify:

nomnom.option('config', {
   flag: true
})

config would get a value of true in the options hash, and test.js would be a free positional arg.

metavar

metavar is used in the usage printout e.g. "PATH" in "-f PATH, --file PATH".

string

A shorthand for abbr, full, and metavar. For example, to attach an option to -c and --config use a string: "-c FILE, --config=FILE"

help

A string description of the option for the usage printout.

default

The value to give the option if it's not specified in the arguments.

type

If you don't want the option JSON-parsed, specify type "string".

callback

A callback that will be executed as soon as the option is encountered. If the callback returns a string it will print the string and exit:

nomnom.option('count', {
   callback: function(count) {
      if (count != parseInt(count)) {
         return "count must be an integer";
      }
   }
})

position

The position of the option if it's a positional argument. If the option should be matched to the first positional arg use position 0, etc.

list

Specifies that the option is a list. Appending can be achieved by specifying the arg more than once on the command line:

node test.js --file=test1.js --file=test2.js

If the option has a position and list is true, all positional args including and after position will be appended to the array.

required

If this is set to true and the option isn't in the args, a message will be printed and the program will exit.

choices

A list of the possible values for the option (e.g. ['run', 'test', 'open']). If the parsed value isn't in the list a message will be printed and the program will exit.

transform

A function that takes the value of the option as entered and returns a new value that will be seen as the value of the option.

nomnom.option('date', {
   abbr: 'd',
   transform: function(timestamp) {
     return new Date(timestamp);
   }
})

hidden

Option won't be printed in the usage

Parser interface

require("nomnom") will give you the option parser. You can also make an instance of a parser with require("nomnom")(). You can chain any of these functions off of a parser:

option

Add an option specification with the given name:

nomnom.option('debug', {
   abbr: 'd',
   flag: true,
   help: "Print debugging info"
})

options

Add options as a hash keyed by option name, good for a cli with tons of options like this example:

nomnom.options({
   debug: {
      abbr: 'd',
      flag: true,
      help: "Print debugging info"
   },
   fruit: {
      help: "Fruit to buy"
   }
})

usage

The string that will override the default generated usage message.

help

A string that is appended to the usage.

autoShowUsage

The enable argument determines if nomnom will automatically print the usage when no commandline argument has been specified at all; the default is true i.e. the feature is enabled. Pass false to disable this feature.

getUsage

Return the generated usage message. When .command(...) has been called before, the usage message for that last 'active' command will be produced.

script

Nomnom can't detect the alias used to run your script. You can use script to provide the correct name for the usage printout instead of e.g. node test.js.

printer

Overrides the usage printing function.

command

Takes a command name and gives you a command object on which you can chain command options.

When you provide a callback function via the .callback() API, then that callback will be invoked when the commandline has been parsed and the given command has been found there. See .callback() for details.

When you did not provide a name argument or a null/undefined name, this API is equivalent to invoking .nocommand().

nocommand

Gives a command object that will be used when no command is called.

When you provide a callback function via the .callback() API, then that callback will be invoked when the commandline has been parsed and either no command has been found there or a command was found for whicch no callback has been specified. See .callback() for details.

nocolors

Disables coloring of the usage message.

setColors

Override the help/report formatting object with your own to provide custom coloring schemes. It should provide these functions:

{
  usageHeadingColor: f1,
  usageStringColor: f2,
  positionalHelpColor: f3,
  optionsHeaderColor: f4,
  helpColor: f5,
  requiredArgColor: f6
};

where f1 through f6 are function references for functions which receive a single string and should return a (processed/transformed) string including the desired coloring console escape sequences.

parse

Parses node's process.argv and returns the parsed options hash. You can also provide argv:

var opts = nomnom.parse(["-xvf", "--atomic=true"])

nom

The same as parse().

Command interface

A command is specified with nomnom.command('name'). All these functions can be chained on a command:

option

Add an option specifically for this command.

options

Add options for this command as a hash of options keyed by name.

callback

A callback that will be called with the parsed options when the command is used. The arguments passed to the callback are a filled options object and the command name.

When the .command() section of the setup code does not specify a callback, then the "fallback callback" will be invoked instead. This callback is the one defined in the .nocommand() a.k.a. empty .command() (without any name argument). Then the command name parameter passed to the provided callback will be null.

help

A help string describing the function of this command.

usage

Override the default generated usage string for this command.

版本与发布记录

@gerhobbelt/nomnom 共发布 17 个版本,首次发布于 2017/08/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.8.4-31latest2021/02/045 年前
1.8.4-302020/04/266 年前
1.8.4-292019/06/247 年前
1.8.4-282019/01/287 年前
1.8.4-272018/09/168 年前
1.8.4-262018/09/168 年前

关于 @gerhobbelt/nomnom 的常见问题

@gerhobbelt/nomnom 是什么?

Option parser with generated usage and commands

如何安装 @gerhobbelt/nomnom?

在项目目录运行 npm install @gerhobbelt/nomnom,或使用 pnpm add / yarn add / bun add。

@gerhobbelt/nomnom 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/gerhobbelt__nomnom 是否存在。

@gerhobbelt/nomnom 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gerhobbelt/nomnom 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=4.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gerhobbelt/nomnom 可以商用吗?

@gerhobbelt/nomnom 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gerhobbelt/nomnom 的下载量有多少?

根据 npm 官方下载统计,@gerhobbelt/nomnom 在 2026/10/16 – 2026/11/14 这 30 天内被下载 42,513 次,日均约 1,417 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gerhobbelt/nomnom 还在维护吗?

最新版本 1.8.4-31 发布于 2021/02/04(5 年前);至今共发布 17 个版本,其中过去 12 个月发布了 0 个;首次发布于 2017/08/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。