Home  >  Q&A  >  body text

node.js - Let me explain the implementation principle of fs module watch in node

Let’s explore the implementation principle of fs module watch in node,

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...");

How does fs implement event notifications in response to file changes? If it is by monitoring file size changes, or something else?

The following are some things seen through the node source code:

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);
    }
  };
}

The fs_event_wrap.cc that follows is basically in alien language.

The data volume I mounted in docker cannot listen to the event notification

ringa_leeringa_lee2674 days ago1140

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-27 17:46:10

    Take a look at this https://github.com/nodejs/nod...

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-27 17:46:10

    Come on, Boy, let’s answer it, you don’t know how to step on me, is there a hole in your head?

    reply
    0
  • Cancelreply