当前位置: 首页 > 后端技术 > Node.js

Nodejs进阶:readline实现日志分析+简单命令行工具

时间:2023-04-03 19:17:50 Node.js

本文节选自《Nodejs学习笔记》,更多章节和更新请访问github主页地址。欢迎加群交流,群号197339705。模块概述readline是一个非常好用的模块。顾名思义,主要用于逐行读取,比如读取用户输入,或者读取文件内容。常见的使用场景有以下几种,本文将一一举例说明。这篇文章的相关代码可以在作者的github上找到。逐行读取文件:例如,用于日志分析。自动补全:比如输入npm,会自动提示“helpinitinstall”。命令行工具:比如npminit,一个问答脚手架工具。基本示例先看一个简单的例子,要求用户输入一个单词,然后自动将其转换为大写constreadline=require('readline');constrl=readline.createInterface({input:process.stdin,output:process.stdout});rl.question('请输入一个词:',function(answer){console.log('你输入了{%s}',answer.toUpperCase());rl.close();});运行如下:?toUpperCasegit:(master)?nodeapp.js请输入一个词:hello你输入了{HELLO}示例:逐行读取文件:日志分析比如我们有如下日志文件access.log,我们要提取“访问时间+访问地址”,借助readline可以轻松完成日志分析。[2016-12-0913:56:48.407][INFO]访问-::ffff:127.0.0.1--“GET/oc/v/account/user.htmlHTTP/1.1”200213125“http://www.example.com/oc/v/account/login.html""Mozilla/5.0(Macintosh;IntelMacOSX10_11_4)AppleWebKit/537.36(KHTML,likeGecko)Chrome/54.0.2840.98Safari/537.36"[2016-12-0914:00:10.618][INFO]访问-::ffff:127.0.0.1--“GET/oc/v/contract/underlying.htmlHTTP/1.1”200216376“http://www.example.com/oc/v/account/user.html""Mozilla/5.0(Macintosh;IntelMacOSX10_11_4)AppleWebKit/537.36(KHTML,likeGecko)Chrome/54.0.2840.98Safari/537.36"[2016-12-0914:00:34.200][信息]访问-::ffff:127.0.0.1--“GET/oc/v/contract/underlying.htmlHTTP/1.1”200216376“http://www.example.com/oc/v/account/user.html""Mozilla/5.0(Macintosh;IntelMacOSX10_11_4)AppleWebKit/537.36(KHTML,likeGecko)Chrome/54.0.2840.98Safari/537.36"代码如下:constreadline=require('readline');constfs=require('fs');constrl=readline.createInterface({input:fs.createReadStream('./access.log')});rl.on('line',(line)=>{constarr=line.split('');console.log('访问时间:%s%s,访问地址:%s',arr[0],arr[1],arr[13]);});运行结果如下:?lineByLineFromFilegit:(master)?nodeapp.js访问时间:[2016-12-0913:56:48.407],访问地址:"http://www.example.com/oc/v/account/login.html”访问时间:[2016-12-0914:00:10.618],访问地址:“http://www.example.com/oc/v/account/user.html”访问时间:[2016-12-0914:00:34.200],访问地址:“http://www.example.com/oc/v/account/user.html”例子:自动补全:代码提示这里我们实现一个简单的自动完成功能。当用户输入npm时,按tab键自动提示用户help、init、install等可选子命令输入np,按tab:自动补全是npm,在里面输入npm,按tab:自动提示optional子命令init和install,输入npminst,按tab:自动补全是npminstallconstreadline=require('readline');constfs=require('fs');函数完成器(行){constcommand='npm';constsubCommands=['help','init','install'];//输入为空,或者是npm的一部分,制表符完成是npmif(line.lengthnpminitinstall示例:command行工具:npmtinit接下来,借助readline实现一个迷你版的npminit函数。运行脚本时,会要求用户依次输入名称、版本、作者属性(其他略过)。这里使用了rl.question(msg,cbk)方法。它会在控制台输入一行提示符。当用户完成输入并回车时,将调用cbk并将用户输入作为参数传入。constreadline=require('readline');constfs=require('fs');constrl=readline.createInterface({输入:process.stdin,输出:process.stdout,提示:'OHAI>'});constpreHint=`此实用程序将引导您创建一个package.json文件。它仅涵盖最常见的项目,并尝试猜测合理的默认值。请参阅\`npmhelpjson\`以获取有关这些字段的权威文档以及它们的确切作用。之后使用\`npminstall--save\`安装一个包并将其作为依赖项保存在package.json文件中。随时按^C退出。`;console.log(preHint);//问题letquestions=['name','version','author'];//默认答案letdefaultAnswers=['name','1.0.0','none'];//用户答案letanswers=[];letindex=0;functioncreatePackageJson(){varmap={};questions.forEach(function(question,index){map[question]=answers[index];});fs.writeFileSync('./package.json',JSON.stringify(map,null,4));}函数ionrunQuestionLoop(){if(index===questions.length){createPackageJson();rl.close();返回;}让defaultAnswer=defaultAnswers[索引];letquestion=questions[index]+':('+defaultAnswer+')';rl.question(question,function(answer){answers.push(answer||defaultAnswer);index++;runQuestionLoop();});}runQuestionLoop();生成的package.json(害羞的脸)?commandLinegit:(master)?nodeapp.js这个实用程序将引导你创建一个package.json文件。它只涵盖最常见的项目,并尝试猜测合理的默认值。见`npmhelpjson`以获得有关这些字段及其作用的权威文档。之后使用`npminstall--save`安装包并将其作为依赖项保存在package.json文件中。随时按^C退出。name:(name)helloversion:(1.0.0)0.0.1author:(none)chyingp基于readline有很多有趣的工具,比如各种脚手架工具。由于篇幅有限,就不展开了,有兴趣的同学可以研究一下。相关链接https://nodejs.org/api/readli...