What is Flutter's version of "tail -f /path/to/log-file.txt"

Viewed 113

I'm trying to do a "tail -f /path/to/log-file.txt" and display the latest log to Flutter. I encountered this

String fileText = await rootBundle.loadString('/path/to/log-file.txt');
print(fileText);

and do a loop every second but the file can be huge so it's better that I get only the latest line that was added to it without having to do an infinite loop like a filechange listener or something.

1 Answers

I tried to implement something like your description. It does not read last line of the file, but the additional strings appended to the file. So this method will cause unexpected behavior if you do something other than appending text to it.

Code:

  var path = '...';

  var file = new File(path);
  var length = file.lengthSync();
  file.watch(events: FileSystemEvent.all).listen((event) {
    file.openRead(length).transform(utf8.decoder).forEach((s) {
      print(s);
      length += s.length;
    });
  });

This method works on my Mac as a native dart project, need more tests for flutter.

Don't forget to cancel the subscription for file.watch when you don't need it.

Related