使用Node.js“ {流式传输”文件的每一行

问题描述

我想逐一读取添加文件中的所有新行,就像它是数据流一样。到目前为止,我正在使用chokidar来接收关于该文件的每次更新的通知,然后,我正在使用read-last-lines传递数字1来表示我只想读一个线。

import fs from 'fs';
const  readLastLines = require('read-last-lines');
import chokidar from 'chokidar';

const logFile = 'log.txt';
// first checks if its exist
if (fs.existsSync(logFile)) { 
  // then start watching on every update
  chokidar.watch(logFile).on('change',(_event,_path) => {
      // read each update
      readLastLines.read(logFile,1)
      .then((line: string) => {
          // do something with this received line.
         // Can't receive two or three lines if sent instantaneously
          doSomething(line);
      }).catch((err :any) => {
        console.log(err)
      })
 })
} else {
  console.log('File Not Found')
}

我工作得很好,除了即时获得两三个文件更新。在这种情况下,我只能得到此更新序列的最后一行。我认为chokidar可能会延迟操作,或者我的操作系统不允许该节点程序同时读取另一个程序正在写入的文件

有人猜我该如何解决?如果它是终端上的程序输出(stdout),我希望它准确运行。 (准确地说,我的海豚是使用它来从客户端记录在我的服务器上运行的程序的。)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)