Nodejs 命令行入门

来源:互联网 发布:长江证券交易软件 编辑:程序博客网 时间:2024/06/06 12:43

前言

关于执行脚本,肯定会想到shell脚本,借助于存量庞大的资源储备,生产力很不错。但上手难度大,语法略显逆天,也是不争的事实。如果可以使用javascript来写脚本,对于前端工程师来说可谓减轻不少工作量。因为工作需求,需要做HTTP LOG分析,虽然最后还是会采用shell脚本,但是会实现一个Node版本。

参考资源

  • http://nodejs.org/api/process.html
  • http://nodejs.org/api/readline.html
  • https://github.com/visionmedia/commander.js
  • https://github.com/SBoudrias/Inquirer.js

文件准备

创建临时工作目录,创建待运行脚本文件。

mkdir workDir;cd workDir;touch sample;chmod u+x sample;npm install commander;npm install inquirer;

脚本编写

Nodejs原生模块processreadline用来处理脚本编写。前者实现命令定义,后者负责交互。先使用readline模块实现让用户输入两个数字,然后求和输出.以下代码即可实现

#!/usr/bin/env nodevar readline = require('readline');var calculator = readline.createInterface(process.stdin, process.stdout);var first, second;calculator.question('what the first number is? \t', function(firstInput) {    first = firstInput;    calculator.question('what the second number is? \t', function(secondInput) {        second = secondInput;        console.log(first + second);        calculator.close();    });});

运行结果如下(没有作数值转换,不要在意这些细节,(*^__^*) 嘻嘻……)

MacdeMacBook-Pro-3:command mac$ ./sumwhat the first number is?  12   what the second number is?  23  1223

再使用process模块伪造简单命令,用以输出所有参数。

#!/usr/bin/env nodeconsole.log(process.argv.slice(2));

运行结果如下,通过process.argv可以获得所有参数,API文档介绍非常清楚。

MacdeMacBook-Pro-3:command mac$ ./sum install koa[ 'install', 'koa' ]

第三方模块

虽然理论上来说利用原生模块即可实现脚本编写,但是需要处理的细节过多,会造成脚本臃肿,所以需要使用第三方模块。commandar, inquirer。前者主要负责脚本功能定义,后者负责交互。需要注意,commandar当前四个交互方法貌似有问题,本机上完全失败,慎用。

#!/usr/bin/env nodevar program = require('commander');var readline = require('readline');program    .version('0.1.0')    .option('-p, --no-peppers', 'Add peppers')    .option('-P, --pineapple', 'Add pineapple')    .option('-n, --name [name]', 'Add bbq sauce');program.parse(process.argv);

执行--help看输出结果,非常熟悉,非常简洁。

MacdeMacBook-Pro-3:command mac$ ./love --help  Usage: love [options]  Options:    -h, --help         output usage information    -V, --version      output the version number    -p, --no-peppers   Add peppers    -P, --pineapple    Add pineapple    -n, --name [name]  Add bbq sauce

再看一下inquire的简单输出

#!/usr/bin/env nodevar inquirer = require('inquirer');var questions = [  {    type: 'checkbox',    name: 'selection',    message: 'select fruits',    choices: [      {        name: 'apple'      },      {        name: 'banana'      },      {        name: 'melon'      }    ]  }];inquirer.prompt(questions, function(answers) {    console.log(answers.selection);})

执行结果如下

MacdeMacBook-Pro-3:command mac$ ./inquir ? select fruits:  ? apple ? banana?? melon

简易文件过滤示例

通道传输数据通过process.stdinprocess.stdout,按照标准的stream处理即可,与commandar结合使用不再赘述。

#!/usr/bin/env nodeprocess.stdin.setEncoding('utf8');process.stdin.on('data', function(chunk) {    var messages = chunk.split('\n').slice(0, -1);    messages.forEach(function(value, key) {        if (value.indexOf(process.argv[2]) !== -1) {            console.log(Date.now() + '\t' + value);        }    })});process.stdin.on('end', function() {    console.log('stdin resolved');});

运行结果如下:

MacdeMacBook-Pro-3:command mac$ lsinquir      love        node_modules    stdin       sumMacdeMacBook-Pro-3:command mac$ ls | ./stdin n1413424753506   inquir1413424753508   node_modules1413424753509   stdinstdin resolved

大功告成,stream处理,在NPM上肯定存在对应封装包,不必深究。

总结

上述第三方示例基本上来自文档示例,如有兴趣,可以自行前往查阅。相当于基础命令行模块,具体的业务实现需要其他的功能模块来实现,不做细究。当前暂时有一个问题,stdin,stderror, stdout处理暂时不太清楚,working on that。

联系方式

QQ: 491229492

0 0
原创粉丝点击