本文介绍了nodejs同步逐行读取大文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大文件(utf8)。我知道 fs.createReadStream
可以创建流来读取大文件,但不能同步。所以我尝试使用 fs.readSync
,但读取的文本像迈
。 var fs = require('fs');
var util = require('util');
var textPath = __dirname +'/people-daily.txt';
var fd = fs.openSync(textPath,r);
var text = fs.readSync(fd,4,0,utf8);
console.log(util.inspect(text,true,null));
解决方案
使用
var lineByLine = require('n-readlines');
var liner = new lineByLine('./ textFile.txt');
var line;
var lineNumber = 0;
while(line = liner.next()){
console.log('Line'+ lineNumber +':'+ line.toString('ascii'));
lineNumber ++;
}
console.log('end of line reached');
I have a large file (utf8). I know fs.createReadStream
can create stream to read a large file, but not synchronized. So i try to use fs.readSync
, but read text is broken like "迈�"
.
var fs = require('fs');
var util = require('util');
var textPath = __dirname + '/people-daily.txt';
var fd = fs.openSync(textPath, "r");
var text = fs.readSync(fd, 4, 0, "utf8");
console.log(util.inspect(text, true, null));
解决方案
use https://github.com/nacholibre/node-readlines
var lineByLine = require('n-readlines');
var liner = new lineByLine('./textFile.txt');
var line;
var lineNumber = 0;
while (line = liner.next()) {
console.log('Line ' + lineNumber + ': ' + line.toString('ascii'));
lineNumber++;
}
console.log('end of line reached');
这篇关于nodejs同步逐行读取大文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!