Monday, February 11, 2019

fs.watchFile() Vs. fs.unwatchFile()

Fs.unwatchFile() function is to stop watching for changes on filename. If the listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of the filename. Calling fs.unwatchFile() with a filename that is not being watched is a co-op, not an error.

Using is more efficient than fs.watchFile() and fs.unwatchFile(). fs,watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.

Here is fs.watchFile() example.

var fs = require('fs');

fs.watchFile('./testFile.txt', function (curr, prev) {
  console.log('the current mtime is: ' + curr.mtime);
  console.log('the previous mtime was: ' + prev.mtime);

fs.writeFile('./testFile.txt', "changed", function (err) {
  if (err) throw err;

  console.log("file write complete");   

And fs.unwatchFile() stops watching for changes on the filename.

No comments:

Post a Comment