Node.js编程快餐(1) - 按行读取文本文件

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;
});
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jtag特工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值