【问题标题】:NodeJS get last line of file everytime file is changed每次更改文件时,NodeJS都会获取文件的最后一行
【发布时间】:2018-11-15 21:10:32
【问题描述】:

我已尝试执行以下操作,但 fs.watch 仅在文件被修改时才被调用,并且我在 notepad++ 中查看 test.txt 文件 我试图让它也被调用,而无需我在记事本中打开 test.txt 来调用函数

const fs = require("fs");
const dir = "test.txt"
fs.watch(dir, (eventType, filename) => {
  fs.readFile(dir, 'utf-8', (err, data) => {

    let lines = data.trim().split("\n")
    console.log(lines[lines.length - 1])
  });
});

【问题讨论】:

  • 使用 fs.watchFile() 代替
  • 啊就是这样,如果你想用那个发布答案,我会接受,谢谢。
  • 您使用的是什么操作系统?怎么修改test.txt?
  • 这实际上取决于您使用的操作系统,watch 将根据平台利用不同的 API。您在哪个平台上运行以及如何与文件交互?
  • 我正在使用 windows,另一个程序写入文件,我只想获取文件的最后一行。 fs.watchFile 为我做了诀窍

标签: javascript node.js file fs


【解决方案1】:

您可以使用文件流创建自己的观察器,每 10 秒触发一次。您也可以在其中添加您的逻辑。

const fs = require('fs');

let previousLine = '';

const readFile = function (path) {
  const fileStream = fs.createReadStream(path, { encoding: 'utf8' });
  let lastLine = '';

  fileStream.on('data', function (value) {
     let linesInStream = value.split(/[\r\n]+/g);
     lastLine = linesInStream[linesInStream.length - 1];
  });

  fileStream.on('end', function () {
    /* will print only when there is change in file content */
    if (lastLine !== previousLine) {
        previousLine = lastLine;
        console.log(lastLine);
    }
  });
};

const waitTime = 10000; // 10 seconds wait

setInterval(function () {
   readFile('C:\\data.log');
}, waitTime);

【讨论】:

  • watch 或类似的实现效率低,您每10 秒读取一次整个文件,而不是仅在发生更改时读取文件.
【解决方案2】:

我需要同样的东西,我把你的代码和这个结合起来:Catch file changes。这是我的代码:

const md5 = require('md5');
console.log('Watching for file changes on ${txt_path}');
let md5Previous = null;
let fsWait = false;
let count = 0;
fs.watch(txt_path, (event , filename) => {
    if(filename){
        if(fsWait) return;
        fsWait = setTimeout( () => {
            fsWait = false;
        }, 100);
        const md5Current = md5(fs.readFileSync(txt_path));
        if (md5Current === md5Previous) {
            return;
        }
        md5Previous = md5Current;
        console.log(`${filename} file Changed`);
        fs.readFile(txt_path, 'utf-8', (err, data) => {
            if (err) throw err;
            let lines = data.trim().split("\n")
            console.log(lines[lines.length - 1])
        })
    }
})

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 2016-12-16
    • 2023-02-21
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多