本文节选自《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.length
