Appearance
可执行脚本
首先,使用 JavaScript 语言,写一个可执行脚本 hello
js
#!/usr/bin/env node
console.log('hello world');然后,修改 hello 的权限:
bash
chmod 755 hello现在,hello 就可以执行了:
bash
$ ./hello
hello world如果想把 hello 前面的路径去除,可以将 hello 的路径加入环境变量 PATH。但是,另一种更好的做法,是在当前目录下新建 package.json ,写入下面的内容:
bash
{
"name": "hello",
"bin": {
"hello": "hello"
}
}然后执行 npm link 命令,现在再执行 hello ,就不用输入路径了:
bash
$ hello
hello world命令行参数的原始写法
js
#!/usr/bin/env node
console.log('hello ', process.argv[2]);执行时,直接在脚本文件后面,加上参数即可:
bash
$ ./hello tom
hello tom上面代码中,实际上执行的是 node ./hello tom ,对应的 process.argv 是 ['node', '/path/to/hello', 'tom']。
新建进程
脚本可以通过 child_process 模块新建子进程,从而执行 Unix 系统命令:
js
#!/usr/bin/env node
var name = process.argv[2];
var exec = require('child_process').exec;
var child = exec('echo hello ' + name, function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});用法如下:
bash
$ ./hello tom
hello tomshelljs 模块
shelljs 模块重新包装了 child_process,调用系统命令更加方便。它需要安装后使用:
bash
npm install --save shelljs然后,改写脚本:
js
#!/usr/bin/env node
var name = process.argv[2];
var shell = require("shelljs");
shell.exec("echo hello " + name);上面代码是 shelljs 的本地模式,即通过 exec 方法执行 shell 命令。此外还有全局模式,允许直接在脚本中写 shell 命令:
js
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 模块能够解决如何处理命令行参数。它也需要安装。
bash
$ npm install --save yargsyargs 模块提供 argv 对象,用来读取命令行参数。请看改写后的 hello:
js
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('hello ', argv.name);使用时,下面两种用法都可以:
bash
$ hello --name=tom
hello tom
$ hello --name tom
hello tom也就是说,process.argv 的原始返回值如下:
$ node hello --name=tom
[ 'node',
'/path/to/myscript.js',
'--name=tom' ]yargs 可以上面的结果改为一个对象,每个参数项就是一个键值对:
js
var argv = require('yargs').argv;
// $ node hello --name=tom
// argv = {
// name: tom
// };如果将 argv.name 改成 argv.n,就可以使用一个字母的短参数形式了:
bash
$ hello -n tom
hello tom可以使用 alias 方法,指定 name 是 n 的别名。
js
#!/usr/bin/env node
var argv = require('yargs')
.alias('n', 'name')
.argv;
console.log('hello ', argv.n);这样一来,短参数和长参数就都可以使用了:
bash
$ hello -n tom
hello tom
$ hello --name tom
hello tomargv 对象有一个下划线(_)属性,可以获取非连词线开头的参数。
js
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('hello ', argv.n);
console.log(argv._);用法如下:
bash
$ hello A -n tom B C
hello tom
[ 'A', 'B', 'C' ]