只需閱讀使用行由行包,更少的頭痛,對讀取過程的更多控制(它可以暫停,繼續閱讀,按需關閉文件描述符,跳過N行),代碼少。
1)安裝:
npm i --save line-by-line
npm i --save lodash
2)實施
var lineByLine = require('line-by-line'),
_ = require('lodash'),
path = require('path');
var lines = [];
var filePath = path.join(__dirname, "ditLogs", file);
var fileReader = new lineByLine(filePath);
fileReader.on('line', function(line) {
line = JSON.parse(line);
if(_.isPlainObject(line) && !_.isEmpty(line)) {
lines.push(line);
}
// optional
doSomethingWithLine(line);
});
function doSomethingWithLine(line) {
// for example You can save to db or send to somewhere using request libary or just show in console
}
fileReader.on('error', function(error) {
console.error(error);
process.exit(-1);
});
fileReader.on('end', function() {
doSomethingAfterParsingAllLines(lines);
});
function doSomethingAfterParsingAllLines(records) {
// do something with data
}
'.split( 「\ n」 個)圖(A => JSON.parse的(a))'? – dandavis