nodejs 逐行读取文件的两种方式
-
通过readline的方式
const fs = require('fs'); const readline = require('readline'); let rl = readline.createInterface({ input: fs.createReadStream("./11.txt") }) rl.on('line', line => { console.log(line); })
-
通过stream的方式
思路:通过流的形式,每次读取一个字节,然后判断这个子节是否是换行符(在mac中换行符为0xa0)
如果不是,则把该字节保存到 临时的数组中,如果是则把这些数组通过Buffer的形式转码utf8
下面的案例是:读取一个文件,然后给每行加行 "",放到一个数组中,然后写入到新的文件中。
const fs = require("fs"); let readStream = fs.createReadStream("./11.txt"); let writeStream = fs.createWriteStream("./11_11.txt"); let buffer = []; function writeFileWithLine(line, isLastLine) { writeStream.write('\t"'); writeStream.write(line); if (isLastLine) { writeStream.write('"\n') } else { writeStream.write('",\n'); } } writeStream.write("[\n"); readStream.on("readable", () => { while ((char = readStream.read(1)) !== null) { if (char[0] === 0x0a) { writeFileWithLine(Buffer.from(buffer).toString(), false); buffer.length = 0; } else { buffer.push(char[0]); } } }); readStream.on("end", () => { writeFileWithLine(Buffer.from(buffer).toString(), true); writeStream.write("]"); });