How to do `tail -f logfile.txt`-like processing in node.js?

后端 未结 5 2232
遇见更好的自我
遇见更好的自我 2020-12-24 01:19

tail -f logfile.txt outputs the last 10 lines of logfile.txt, and then continues to output appended data as the file grows.

What\'s the recommended way

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 02:13

    you can try to use fs.read instead of ReadStream

    var fs = require('fs')
    
    var buf = new Buffer(16);
    buf.fill(0);
    function read(fd)
    {
        fs.read(fd, buf, 0, buf.length, null, function(err, bytesRead, buf1) {
            console.log(buf1.toString());
            if (bytesRead != 0) {
                read(fd);
            } else {
                setTimeout(function() {
                    read(fd);
                }, 1000);
            }
        }); 
    }
    
    fs.open('logfile', 'r', function(err, fd) {
        read(fd);
    });
    

    Note that read calls callback even if there is no data and it just reached end of file. Without timeout you'll get 100% cpu here. You could try to use fs.watchFile to get new data immediately.

提交回复
热议问题