NodeJS 命令行开发

2018/08/25 npmnodeshell

# 可执行脚本

首先,使用 JavaScript 语言,写一个可执行脚本 hello

#!/usr/bin/env node
console.log('hello world');

然后,修改 hello 的权限:

chmod 755 hello

现在,hello 就可以执行了:

$ ./hello
hello world

如果想把 hello 前面的路径去除,可以将 hello 的路径加入环境变量 PATH。但是,另一种更好的做法,是在当前目录下新建 package.json ,写入下面的内容:

{
    "name": "hello",
    "bin": {
        "hello": "hello"
    }
}

然后执行 npm link 命令,现在再执行 hello ,就不用输入路径了:

$ hello
hello world

# 命令行参数的原始写法

#!/usr/bin/env node
console.log('hello ', process.argv[2]);

执行时,直接在脚本文件后面,加上参数即可:

$ ./hello tom
hello tom

上面代码中,实际上执行的是 node ./hello tom ,对应的 process.argv['node', '/path/to/hello', 'tom']

# 新建进程

脚本可以通过 child_process 模块新建子进程,从而执行 Unix 系统命令:

#!/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);
});

用法如下:

$ ./hello tom
hello tom

# shelljs 模块

shelljs (opens new window) 模块重新包装了 child_process,调用系统命令更加方便。它需要安装后使用:

npm install --save shelljs

然后,改写脚本:

#!/usr/bin/env node
var name = process.argv[2];
var shell = require("shelljs");

shell.exec("echo hello " + name);

上面代码是 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' ]

# 参考资料

上次更新: 2024/4/15 02:28:03