浅谈node.js 命令行工具(cli)

2020-06-17 06:52:08易采站长站整理


$ npm link

执行后会产生一个全局的映射关系,就可以全局使用hello命令了

三.命令行参数

命令行参数可以用系统变量 process.argv 获取。

修改hello脚本


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

其中process为node进程中的全局变量,process.argv为一数组,数组内存储着命令行的各个部分,argv[0]为node的安装路径,argv[1]为主模块文件路劲,剩下为子命令或参数,如下:

$ hello a b c

# process.argv的值为[ '/usr/local/bin/node', '/usr/local/bin/hello', 'a', 'b', 'c' ]

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

exec
方法用于执行bash命令,
exec
方法最多可以接受两个参数,第一个参数是所要执行的shell命令,第二个参数是回调函数,该函数接受三个参数,分别是发生的错误、标准输出的显示结果、标准错误的显示结果。


#!/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 litongqian

如果我们想查看所有文件,修改hello


var name = process.argv[2];
var exec = require('child_process').exec;

var child = exec(name, function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});

执行$ hello ls 

hello目录下有三个文件

四、shelljs 模块

shell.js 模块重新包装了 child_process,调用系统命令更加方便。它需要安装后使用。


npm install --save shelljs

然后,改写脚本。


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

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

五、yargs 模块

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


$ npm install --save yargs

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