來探討node中fs模組watch實作原理,
const fs = require('fs');
var fileName = 'a.txt';
fs.watch(fileName, (function () {
var count = 0;
return function () {
count++;
console.log("文件" + fileName + " 内容刚刚改变。。第" + count + "次");
};
})());
console.log("watching file...");
fs如何實現針對檔案變更做出回應的事件通知的呢?如果說是透過監聽檔案大小變化,或者其他?
下面是透過node原始碼看到的一些東西:
const FSEvent = process.binding('fs_event_wrap').FSEvent;
function FSWatcher() {
EventEmitter.call(this);
var self = this;
this._handle = new FSEvent();
this._handle.owner = this;
this._handle.onchange = function(status, eventType, filename) {
if (status < 0) {
self._handle.close();
const error = !filename ?
errnoException(status, 'Error watching file for changes:') :
errnoException(status,
`Error watching file ${filename} for changes:`);
error.filename = filename;
self.emit('error', error);
} else {
self.emit('change', eventType, filename);
}
};
}
後面的fs_event_wrap.cc 基本上都是外星語了。
下面我再docker當中掛載的資料卷監聽不到事件通知