对于大文件,readFileSync
可能会很不方便,因为它将整个文件加载到内存中。一种不同的同步方法是迭代调用readSync
,一次读取少量数据,并在行到来时对其进行处理。以下代码实现了这种方法,并一次从文件“test.txt”同步处理一行:
var fs = require('fs');
var filename = 'test.txt'
var fd = fs.openSync(filename, 'r');
var bufferSize = 1024;
var buffer = new Buffer(bufferSize);
var leftOver = '';
var read, line, idxStart, idx;
while ((read = fs.readSync(fd, buffer, 0, bufferSize, null)) !== 0) {
leftOver += buffer.toString('utf8', 0, read);
idxStart = 0
while ((idx = leftOver.indexOf("\n", idxStart)) !== -1) {
line = leftOver.substring(idxStart, idx);
console.log("one line read: " + line);
idxStart = idx + 1;
}
leftOver = leftOver.substring(idxStart);
}