我们如何在不使用外部包和 tail -f 的情况下继续观察大型日志文件并使用 node.js 输出最后 10 行?

How can we keep watching a large log file and output the last 10 lines using node.js without using external package and tail -f?

我的服务器上有一个很大的日志文件,我想继续查看该日志文件并只获取该日志文件的最后 10 行,而不使用 tail -f 或任何其他提供相同功能的包unix 中的 tail -f。

我们可以通过从头开始遍历日志文件并获取最后 10 行来做到这一点,但如果日志文件很大,则会产生问题。

让我知道是否还有其他选择?

谢谢!

模仿tail -n的(可能是幼稚的)尝试:

import fs from 'fs';

const path = 'test.txt';
const lastLinesLimit = 5;

const fileSize = fs.statSync(path).size;
const fd = fs.openSync(path);

// Increase the next number appropriately to decrease read calls.
let bufferSize = Math.min(10, fileSize);
let buffer = Buffer.alloc(bufferSize);

let stringTail = '';
let position = fileSize;

while (position !== 0) { // Rapeat from end till start of file.
  position -= bufferSize; // Step back by buffer size.

  if (position < 0) { // In case we reach too far:
    bufferSize += position; // decrease buffer size to read just what remains,
    buffer = buffer.subarray(0, position); // decrease buffer appropriately,
    position = 0; // set position at start of file.
  }

  fs.readSync(fd, buffer, 0, bufferSize, position); // Read a chunk.
  stringTail = buffer.toString() + stringTail; // Prepend to previously read data.
  if (stringTail.match(/\n(?!$)/g)?.length >= lastLinesLimit) break; // Check if we have enough lines.
}

console.log(
  stringTail
    .split(/\n(?!$)/)
    .slice(-lastLinesLimit)
    .join('\n')
);