是否有一个相当于 Node.js 的 Python argparse 的模块?
argparse for python 可以快速轻松地处理命令行输入、处理位置参数、可选参数、标志、输入验证等等。我已经开始在 Node.js 中编写应用程序,并且发现手动编写所有这些内容既乏味又耗时。
有没有一个node.js 模块可以处理这个问题?
argparse for python makes it quick and easy to handle command-line input, handling positional arguments, optional arguments, flags, input validation and much more. I've started writing applications in node.js and I'm finding it tedious and time consuming to write all that stuff manually.
Is there a node.js module for handling this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有一个直接端口,方便地也称为 argparse。
There is one direct port, conveniently also called argparse.
https://github 上有大量各种命令行参数处理程序。 com/joyent/node/wiki/modules#wiki-parsers-commandline
我在大多数项目中使用的是 https://github.com/visionmedia/commander.js 不过我会看一下所有这些,看看哪一个适合您的特定需求。
There are a slew of various command line argument handlers at https://github.com/joyent/node/wiki/modules#wiki-parsers-commandline
The one I use in most projects is https://github.com/visionmedia/commander.js though I would take a look at all of them to see which one suits your specific needs.
在 18.3.0 中,nodejs 增加了一个核心功能
util.parseArgs([config])
详细文档可在此处获取:https://github.com/pkgjs/parseargs#faqs
In 18.3.0 nodejs has landed a core addition
util.parseArgs([config])
Detailed documentation is available here: https://github.com/pkgjs/parseargs#faqs
有 yargs,它似乎非常完整且有据可查。
There's yargs, which seems to be pretty complete and well documented.
以下是一些简单的样板代码,允许您提供命名参数:
用法示例:
您还可以添加一组接受的名称,并在提供无效名称时抛出异常:
Here is some simple boilerplate code which allows you to provide named args:
Example usage:
You can also add a
Set
of accepted names and throw exception if an invalid name is provided:以下是 Node 18 的
util.parseArgs
库的示例:ArgumentParser 包装器类
我编写了一个包装器,其行为与 Python 中的
argparse
库非常相似。任何实际上未传递到内部util.parseArgs
的选项都会添加到私有Map
中,并在显示帮助时获取。注意:这是 Python argparse 库的精简版本,因此并不完整。
用法
输出
我为 kebab-case、camelCase 和 UPPER_SNAKE_CASE(也称为 SCREAMING_SNAKE_CASE)编写了自己的大小写转换策略,但您可以使用
js-convert-case
npm 模块代替。Here is an example of Node 18's
util.parseArgs
library:ArgumentParser wrapper class
I wrote a wrapper that acts very similar to the
argparse
library in Python. Any option that does not actually get passed to the internalutil.parseArgs
is added to a privateMap
and fetched when displaying the help.Note: This is a stripped-down version of Python's
argparse
library, so this is not complete.Usage
Output
I wrote my own case conversion strategy for kebab-case, camelCase, and UPPER_SNAKE_CASE (also referred to as SCREAMING_SNAKE_CASE), but you could us the
js-convert-case
npm module instead.