使用 process.argv 获取参数
process.argv 属性返回一个数组,其中包含当启动Node.is 进程时传入的命令行参数。
第一个元素是 process.execPath。第二个元素将是正在执行的 JavaScript 文件的路径。 其余元素就是命令的传参
示例:
//process-args.js
process.argv.forEach((val, index) => {
console.log( $findex}: ${val]')
})
//run
$ node process-args.js one two=three four
//output
0: /usr/local/bin/node
1:/Users/mjr/work/node/process-args.js
2:one
3:two=three
4.four
更好的参数获取方式 commander.js
支持链式调用
更好的数处理
autohelp
示例:
#!/usr/bin/env node
//commander.js
const program = require( 'commander');
const getHelp = () => {}
program
.name('better-clone')
.version('0.0.1')
.option('-v,--verbose', 'verbosity that can be increased')
program
.command('clone <source> [destination]')
.option('-d,--depths <level>','git clone depths')
.description('clone a repository into a newly created directory')
.action(( source, destination, cmdObj) => {
console.log(`${source} , ${destination} , ${cmdObj}`)
//...
});
program.parse(process .argv);
//run commander.js
$ node ./src/commander.js clone ./src ./target --depath=2
//output
./src , ./target , depath 2
CLI交互 - 输入
不借助工具的情况经常会面临以下几个问题:
- 命令太长,用户很难记住
- 参数太多,很容易配置错误
- 不想再history中留下痕迹
CLI更友好的输入交互 - Inquirerjs
灵活的CLI交互方式:
- input
- expand
- number
- checkbox
- confirm
- password
- list
- Editor
- rawlist
- ...
抹平平台间差异 :兼容Windows/0SX/Linux上的主流终端,不用关心平台底层实现细节
示例:
const inquirer = require( 'inquirer')
inquirer
.prompt([
/* Passyour questionsin here */
{ type: 'input', name:'username' , message: "what's yur name?"},
{
type: 'checkbox',
name: 'gender',
message: "What's yur gender?",
choices: [ 'male', 'female']
},
{
type: 'number',
name: ' age' ,
message: 'How old are u?',
validate: input => Number.isNaN(Number( input ))? 'Number Required!' : true
}
{
type: ' password',
name: ' secret' ,
message: 'Tell me a secret.',
mask: 'x'
}
])
.then(answers => {
console.log(`Answers are:\n ${answers}`)
})
.catch(error => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else when wrong
}
})
CLI更友好的输出交互 - chalk
错误提示,希望醒目提醒
操作成功,希望给用户正面反馈
用户搜索关键词,希望高亮显示
例子:
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('\nHello') + world' + chalk.red('!\n'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold( 'Hello world!\n' ));
//pass in multiple arguments
log(chalk.blue( 'Hello','world!','Foo','bar','biz','baz\n' ));
调用其他程序
shell js
对bash命令提供了跨平台的封装
可以同步的获得命令结果
示例:
const shell = require( 'shelljs');
if (!shell.which( 'git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf','out/Release' );
//Replace macros in eachis file
shell.ls('*.js').forEach( function (file) {
shell.sed('-i','BUILD VERSION','v0.1.2', file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
execa
结果Promise化
跨平台支持Shebang
获取进程结束信号
优雅退出
更好的Windows支持
const execa = require( 'execa');
(async () => {
const {stdout} = await execa( 'echo', [ 'unicorns']);
console.log( stdout);
//...
})();