Node.js与其它语言一样,提供了对文本文件按照行来读的功能。不过与Ruby,Python等语言不同,Node.js的File System对象并不提供迭代访问功能。
比如在Ruby中可以这么写
file = File.new("log1.log")
file.each do |line|
puts line if line =~ /blablabla/
end
在Python中,这个文件迭代可以这么写(为了Python3,我给print加了括号):
f = open('log1.log','r')
for eachLine in f:
print (eachLine)
f.close()
经姚军勇同学review,认为上面的python版本写得不好,下面是改进版:
with open("log1.log", "r") as file:
[print(x) for x in file.readlines()]
但是在Node.js中,要借用一个独立模块readline来实现这个功能:
"use strict"
const readline = require('readline')
const fs = require("fs");
const r1 = readline.createInterface({
input: fs.createReadStream("log1.log")
});
var i = 1;
r1.on('line', (line) => {
console.log('Line from file:' + i + ":" + line);
i += 1;
});
网友评论