繁体   English   中英

使用 NodeJs 读取大文件的最后一行

[英]Read last line of a large file with NodeJs

我正在使用 这个例子来读取一个大文件:

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何时是文件的最后一行。 我阅读了文档,但找不到解决方案。 我已经尝试过:

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)
    })

将您收到的行保存在全局变量中,然后在到达文件末尾时显示它。

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

    lastLine = line;
});

我在我的 mocha 测试套件中使用了exec(tail -n 1 <filepath>)因为我确切地知道它做什么并且它用更少的代码行完成它......

虽然在构建应用程序时可能不太理想

const { exec } = require("child_process");
exec("tail -n 1 nginx_access.log",  (error, stdout, stderr) => {
   console.log(stdout)
})

保存当前行,当您到达文件末尾时,您将获得最后一行。 当输入流的所有数据都被消耗时,它会发出一个“结束”事件。 https://nodejs.org/api/stream.html#stream_event_end

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);

var currentLine;

rl.on('line', function(line) {
    currentLine = line;

    // process line here
});

instream.on('end', function() {
    // currentLine is now the last line
    // use currentLine here
});

您也可以使用rl.on('end')事件,但它会因更多原因而发出,例如中断或调用rl.close() ,但这些可能不会影响您。 https://nodejs.org/api/readline.html#readline_event_close

为了有效地读取大文件的最后 N 行,我们可以使用这个 npm 包read-last-lines

https://www.npmjs.com/package/read-last-lines

读取文件最后 50 行的示例:

const readLastLines = require('read-last-lines');
readLastLines.read('path/to/file', 50)
    .then((lines) => console.log(lines));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM