详解Node.js 命令行程序开发教程

2020-06-17 06:49:11易采站长站整理

上面代码是 shelljs 的本地模式,即通过 exec 方法执行 shell 命令。此外还有全局模式,允许直接在脚本中写 shell 命令。


require('shelljs/global');

if (!which('git')) {
echo('Sorry, this script requires git');
exit(1);
}

mkdir('-p', 'out/Release');
cp('-R', 'stuff/*', 'out/Release');

cd('lib');
ls('*.js').forEach(function(file) {
sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
sed('-i', /.*REMOVE_THIS_LINE.*n/, '', file);
sed('-i', /.*REPLACE_LINE_WITH_MACRO.*n/, cat('macro.js'), file);
});
cd('..');

if (exec('git commit -am "Auto-commit"').code !== 0) {
echo('Error: Git commit failed');
exit(1);
}

五、yargs 模块

shelljs 只解决了如何调用 shell 命令,而 yargs 模块能够解决如何处理命令行参数。它也需要安装。


$ npm install --save yargs

yargs 模块提供 argv 对象,用来读取命令行参数。请看改写后的 hello 。


#!/usr/bin/env node
var argv = require('yargs').argv;

console.log('hello ', argv.name);

使用时,下面两种用法都可以。


$ hello --name=tom
hello tom

$ hello --name tom
hello tom

也就是说,process.argv 的原始返回值如下。


$ node hello --name=tom
[ 'node',
'/path/to/myscript.js',
'--name=tom' ]

yargs 可以上面的结果改为一个对象,每个参数项就是一个键值对。


var argv = require('yargs').argv;

// $ node hello --name=tom
// argv = {
// name: tom
// };

如果将 argv.name 改成 argv.n,就可以使用一个字母的短参数形式了。


$ hello -n tom
hello tom

可以使用 alias 方法,指定 name 是 n 的别名。


#!/usr/bin/env node
var argv = require('yargs')
.alias('n', 'name')
.argv;

console.log('hello ', argv.n);

这样一来,短参数和长参数就都可以使用了。


$ hello -n tom
hello tom
$ hello --name tom
hello tom

argv 对象有一个下划线(_)属性,可以获取非连词线开头的参数。


#!/usr/bin/env node
var argv = require('yargs').argv;

console.log('hello ', argv.n);
console.log(argv._);

用法如下。


$ hello A -n tom B C
hello tom
[ 'A', 'B', 'C' ]