cli 中文文档教程
cli 是一个用于快速构建命令行应用程序的工具包 - 它包括:
- Full featured opts/args parser
- Plugin support for adding common options and switches
- Helper methods for working with input/output and spawning child processes
- Output colored/styled messages, progress bars or spinners
- Command auto-completion and glob support
使用 npm install cli
安装或仅捆绑 cli.js 与您的应用程序。
Example apps
sort.js
#!/usr/bin/env node
require('cli').withStdinLines(function(lines, newline) {
this.output(lines.sort().join(newline));
});
试试吧 让
$ ./sort.js < input.txt
我们添加对 -n
开关的支持以使用数字排序,以及 -r
开关以反向输出 - 仅增加 5 行代码 (!)
var cli = require('cli'), options = cli.parse();
cli.withStdinLines(function(lines, newline) {
lines.sort(!options.n ? null : function(a, b) {
return parseInt(a) > parseInt(b);
});
if (options.r) lines.reverse();
this.output(lines.join(newline));
});
Command Line Arguments Parser
cli将对象作为您希望解析的参数的映射。
对象中的每个属性/键都是参数的长版本,即 --file
与之关联的数组是应用于该参数的选项。
Example
cli.parse({
file: [ 'f', 'A file to process', 'file', temp.log ], // -f, --file FILE A file to process
time: [ 't', 'An access time', 'time', false], // -t, --time TIME An access time
work: [ false, 'What kind of work to do', 'string', 'sleep' ] // --work STRING What kind of work to do
});
Explanation of array options
- A short name, single letter i.e. -f, or false if no short name is supported for this option
- A description of the option
- The type of object the argument should map too.
Below is a list of the return types followed by a description and a list of
valid values you can use for this option to get desired type of Object back.- as-is: What you enter, is what you get
- 'string', 1, true
- as-is: What you enter, is what you get
- int: Is converted to an Integer wrapped in a Number Object - 'int', 'number', 'num', - 'time', 'seconds', 'secs', 'minutes', 'mins' - 'x', 'n'
- date: Is converted to a Date Object - 'date', 'datetime', 'date_time'
- float: Is converted to a Float wrapped in a Number Object
- 'float', 'decimal'
- file: Is converted to a String Object if it is a valid path
- 'path', 'file', 'directory', 'dir'
- email: Converted to a String Object if it is a valid email format
- 'email'
- url: Converted to a String Object if it is a valid URL format
- 'url', 'uri', 'domain', 'host'
- float: Is converted to a Float wrapped in a Number Object
- ip: Converted to a String Object if it is a valid IP Address format - 'ip'
- true: Converted to true if argument is present on command line - 'bool', 'boolean', 'on'
- false: Converted to false if argument is present on command line
- 'false', 'off', false, 0
- false: Converted to false if argument is present on command line
- A default value for this option if one is not given on the command line
Helper methods
cli 有收集标准输入的方法(换行符被自动检测为 \n 或 \r\n)
cli.withStdin(callback); //callback receives stdin as a string
cli.withStdinLines(callback); //callback receives stdin split into an array of lines (lines, newline)
cli 还有一个较低级别的方法来逐行处理输入(参见 ./examples/cat.js)。
cli.withInput(file, function (line, newline, eof) {
if (!eof) {
this.output(line + newline);
}
});
注意:file
可以省略,如果你想使用 stdin
//cli.toType(object); If a Built-in type, returns the name of the type as a lower cased String
cli.toType([]); // 'array'
cli.toType(new Date()); // 'date'
cli.toType(1); // 'integer'
cli.toType(1.1); // 'float'
cli.toType(Math); // 'math'
cli.toType(/a/); // 'regex'
cli.toType(JSON); // 'json'
要输出进度条,调用
cli.progress(progress); //Where 0 <= progress <= 1
要生成子进程,使用
cli.exec(cmd, callback); //callback receives the output of the process (split into lines)
cli 也与 kof 的 node-natives(通过 cli.native 访问)和 creationix' stack(通过 cli.createServer 访问)
Plugins
插件是一种添加常用选项的方式,可以使用
cli.enable(plugin1, [plugin2, ...]); //To disable, use the equivalent disable() method
帮助启用 - 默认启用
添加 -h,--help
输出自动生成的使用信息
version
添加 -v,--version
输出应用程序的版本信息。 cli 将尝试定位并解析附近的 package.json
要设置您自己的应用名称和版本,请使用 cli.setApp(app_name, version)
status
添加选项以显示/隐藏使用这些方法之一时输出到控制台的程式化状态消息
cli.debug(msg); //Only shown when using --debug
cli.error(msg);
cli.fatal(msg); //Exits the process after outputting msg
cli.info(msg);
cli.ok(msg);
-k,--no-color
将从输出中省略 ANSI 颜色转义
glob - requires npm install glob
启用参数的 glob 匹配
timeout
添加 -t,--timeout N 在 N 秒后出错退出进程
catchall
添加 -c,--catch
以捕获并输出 uncaughtExceptions 并恢复执行
注意:插件是自动的如果已定义同名选项或开关则禁用
LICENSE
(MIT 许可证)
版权所有 (c) 2010 Chris O'Hara cohara87@gmail.com< /a>
特此免费授予任何获得许可的人 此软件和相关文档文件的副本( “软件”),不受限制地处理软件,包括 但不限于使用、复制、修改、合并、发布、 分发、再许可和/或出售软件的副本,以及 允许向其提供软件的人这样做,但须遵守 下列条件:
上述版权声明和本许可声明应 包含在软件的所有副本或重要部分中。
本软件“按原样”提供,不提供任何形式的保证, 明示或暗示的,包括但不限于 适销性、特定用途的适用性和 非侵权。 在任何情况下,作者或版权持有人均不得 对任何索赔、损害或其他责任负责,无论是在诉讼中 合同、侵权行为或其他由其引起、由其引起或与之相关的 与软件或软件的使用或其他交易。
cli is a toolkit for rapidly building command line apps - it includes:
- Full featured opts/args parser
- Plugin support for adding common options and switches
- Helper methods for working with input/output and spawning child processes
- Output colored/styled messages, progress bars or spinners
- Command auto-completion and glob support
Install using npm install cli
or just bundle cli.js with your app.
Example apps
sort.js
#!/usr/bin/env node
require('cli').withStdinLines(function(lines, newline) {
this.output(lines.sort().join(newline));
});
Try it out
$ ./sort.js < input.txt
Let's add support for an -n
switch to use a numeric sort, and a -r
switch to reverse output - only 5 extra lines of code (!)
var cli = require('cli'), options = cli.parse();
cli.withStdinLines(function(lines, newline) {
lines.sort(!options.n ? null : function(a, b) {
return parseInt(a) > parseInt(b);
});
if (options.r) lines.reverse();
this.output(lines.join(newline));
});
Command Line Arguments Parser
cli takes an object as a map for the arguments you wish to parse.
Each property/key in the object is the long version of the argument i.e. --file
The array associated with it is the options to apply to that argument.
Example
cli.parse({
file: [ 'f', 'A file to process', 'file', temp.log ], // -f, --file FILE A file to process
time: [ 't', 'An access time', 'time', false], // -t, --time TIME An access time
work: [ false, 'What kind of work to do', 'string', 'sleep' ] // --work STRING What kind of work to do
});
Explanation of array options
- A short name, single letter i.e. -f, or false if no short name is supported for this option
- A description of the option
- The type of object the argument should map too.
Below is a list of the return types followed by a description and a list of
valid values you can use for this option to get desired type of Object back.- as-is: What you enter, is what you get
- 'string', 1, true
- as-is: What you enter, is what you get
- int: Is converted to an Integer wrapped in a Number Object - 'int', 'number', 'num', - 'time', 'seconds', 'secs', 'minutes', 'mins' - 'x', 'n'
- date: Is converted to a Date Object - 'date', 'datetime', 'date_time'
- float: Is converted to a Float wrapped in a Number Object
- 'float', 'decimal'
- file: Is converted to a String Object if it is a valid path
- 'path', 'file', 'directory', 'dir'
- email: Converted to a String Object if it is a valid email format
- 'email'
- url: Converted to a String Object if it is a valid URL format
- 'url', 'uri', 'domain', 'host'
- float: Is converted to a Float wrapped in a Number Object
- ip: Converted to a String Object if it is a valid IP Address format - 'ip'
- true: Converted to true if argument is present on command line - 'bool', 'boolean', 'on'
- false: Converted to false if argument is present on command line
- 'false', 'off', false, 0
- false: Converted to false if argument is present on command line
- A default value for this option if one is not given on the command line
Helper methods
cli has methods that collect stdin (newline is auto-detected as \n or \r\n)
cli.withStdin(callback); //callback receives stdin as a string
cli.withStdinLines(callback); //callback receives stdin split into an array of lines (lines, newline)
cli also has a lower level method for working with input line by line (see ./examples/cat.js for an example).
cli.withInput(file, function (line, newline, eof) {
if (!eof) {
this.output(line + newline);
}
});
Note: file
can be omitted if you want to work with stdin
//cli.toType(object); If a Built-in type, returns the name of the type as a lower cased String
cli.toType([]); // 'array'
cli.toType(new Date()); // 'date'
cli.toType(1); // 'integer'
cli.toType(1.1); // 'float'
cli.toType(Math); // 'math'
cli.toType(/a/); // 'regex'
cli.toType(JSON); // 'json'
To output a progress bar, call
cli.progress(progress); //Where 0 <= progress <= 1
To spawn a child process, use
cli.exec(cmd, callback); //callback receives the output of the process (split into lines)
cli also comes bundled with kof's node-natives (access with cli.native) and creationix' stack (access with cli.createServer)
Plugins
Plugins are a way of adding common opts and can be enabled using
cli.enable(plugin1, [plugin2, ...]); //To disable, use the equivalent disable() method
help - enabled by default
Adds -h,--help
to output auto-generated usage information
version
Adds -v,--version
to output version information for the app. cli will attempt to locate and parse a nearby package.json
To set your own app name and version, use cli.setApp(app_name, version)
status
Adds options to show/hide the stylized status messages that are output to the console when using one of these methods
cli.debug(msg); //Only shown when using --debug
cli.error(msg);
cli.fatal(msg); //Exits the process after outputting msg
cli.info(msg);
cli.ok(msg);
-k,--no-color
will omit ANSI color escapes from the output
glob - requires npm install glob
Enables glob matching of arguments
timeout
Adds -t,--timeout N
to exit the process after N seconds with an error
catchall
Adds -c,--catch
to catch and output uncaughtExceptions and resume execution
Note: Plugins are automatically disabled if an option or switch of the same name is already defined
LICENSE
(MIT license)
Copyright (c) 2010 Chris O'Hara cohara87@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.