gpt4 book ai didi

node.js - 使用 NodeJs 读取大文件的最后一行

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:44 25 4
gpt4 key购买 nike

我正在使用this example读取大文件:

var fs = require('fs');
var readline = require('readline');
var stream = require('stream');

var instream = fs.createReadStream('your/file');
var outstream = new stream;
var rl = readline.createInterface(instream, outstream);

rl.on('line', function(line) {
// process line here
});

rl.on('close', function() {
// do something on finish here
});

我想知道line何时是文件的最后一行。我读了docs但找不到解决办法。我已经尝试过了:

rl.on('line', function(line) {
if (line == '' || line == require("os").EOL)
console.log('eof');
});

但是没有成功。
你有什么建议吗。感谢您的阅读。

最佳答案

Axel 的答案的问题是他假设文件的最后一行将为空或 EOL。事实并非如此。

// fileTools.js
const fs = require('fs');
const readline = require('readline');
const Stream = require('stream');

exports.getLastLine = (fileName, minLength) => {
let inStream = fs.createReadStream(fileName);
let outStream = new Stream;
return new Promise((resolve, reject)=> {
let rl = readline.createInterface(inStream, outStream);

let lastLine = '';
rl.on('line', function (line) {
if (line.length >= minLength) {
lastLine = line;
}
});

rl.on('error', reject)

rl.on('close', function () {
resolve(lastLine)
});
})
}

使用:

const getLastLine = require('./fileTools.js').getLastLine
const fileName = 'C:\\someWinDir\\somelog.log'
const minLineLength = 1
getLastLine(fileName, 1)
.then((lastLine)=> {
console.log(lastLine)
})
.catch((err)=> {
console.error(err)
})

关于node.js - 使用 NodeJs 读取大文件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40107433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com