无限文件观察者

时间:2014-06-06 07:19:23

标签: dart

您好我正在尝试在Dart中实现文件观察程序。而问题是我无法弄清楚如何为流做永远的lister。在我的代码中print语句只在文件被更改时触发一次。我试过while(true){}但没有影响。

import "dart:io";


void main(){
  List<String> paths = ['any.dart'];
  paths.forEach((fp){
    File f = new File(fp);
    f.watch().listen((e){
      print(e);
    });
  });
}

飞镖信息:Dart VM version: 1.4.0 (Tue May 20 04:56:35 2014) on "linux_x64"

3 个答案:

答案 0 :(得分:3)

请查看监视功能的文档:

The implementation uses platform-dependent event-based APIs for receiving file-system notifications, thus behavior depends on the platform. 

* Windows: Uses ReadDirectoryChangesW. The implementation only 
    supports watching directories. Recursive watching is supported.

* `Linux`: Uses `inotify`. The implementation supports watching both 
    files and directories. Recursive watching is not supported.
    Note: When watching files directly, delete events might not happen
    as expected.

* `Mac OS`: Uses `FSEvents`. The implementation supports watching both 
    files and directories. Recursive watching is supported.

这意味着这不适用于Windows。对于你的问题,它说:

The returned value is an endless broadcast [Stream], that only stops when
one of the following happends:

  * The [Stream] is canceled, e.g. by calling `cancel` on the
     [StreamSubscription].
  * The [FileSystemEntity] being watches, is deleted.

这意味着您的文件被删除,流被取消或这是一个错误,您应该为此提交一张票。

在Windows上对我没有任何反应。在Mac上,我用你的代码得到了这个:

FileSystemModifyEvent('test_file_watcher.dart', contentChanged=true)
FileSystemModifyEvent('test_file_watcher.dart', contentChanged=true)
FileSystemModifyEvent('test_file_watcher.dart', contentChanged=true)
FileSystemModifyEvent('test_file_watcher.dart', contentChanged=true)
FileSystemModifyEvent('test_file_watcher.dart', contentChanged=true)
FileSystemModifyEvent('test_file_watcher.dart', contentChanged=true)

您如何测试代码?我简单编辑并保存了我的文件。所以它对我很有用。你使用的是哪个版本?

此致 罗伯特

答案 1 :(得分:1)

更新:

import "dart:io";

void main() {
  var fileName = 'test.txt';
  var file = new File(fileName);
  var dir = file.parent;
  var flag = true;
  dir.watch().listen((e) {
    if(e is FileSystemModifyEvent){
      if (e.path.endsWith(fileName) && (flag = !flag))
        print("do something");
    }
    else{
      if (e.path.endsWith(fileName))
        print("do something");
    }
  });
}

答案 2 :(得分:1)

我的最终版本是(受JAre启发)     

import "dart:io";


void main(){
  List<String> paths = ['main.dart'];
  paths.forEach((fp){
      File f = new File(fp);
      f.parent.watch().listen((e){
        if(e is FileSystemMoveEvent && e.destination == fp){
           print('Modified with temp file');
        }
        if(e is FileSystemModifyEvent  && e.path == fp){
           print('Modified in place');
        }
      });
  });
}

根据JAre的评论更新