📜  Node.js fs.unwatchFile() 方法

📅  最后修改于: 2022-05-13 01:56:27.984000             🧑  作者: Mango

Node.js fs.unwatchFile() 方法

fs.unwatchFile() 方法用于停止监视给定文件的更改。可以指定可选的侦听器参数以仅从文件中删除指定的侦听器。否则,与该文件关联的所有侦听器都将被删除。如果使用此函数时文件没有被监视,则它不执行任何操作并抛出任何错误。

句法:

fs.unwatchFile(filename[, listener])

参数:此方法接受上面提到的两个参数,如下所述:

  • 文件名:它是一个字符串、缓冲区或 URL,表示必须停止观看的文件。
  • 监听器:它是一个函数,它指定先前使用 fs.watchFile()函数附加的监听器。如果指定,则仅删除此特定侦听器。它是一个可选参数。

下面的示例说明了 Node.js 中的fs.unwatchFile() 方法

示例 1:

// Node.js program to demonstrate the 
// fs.unwatchFile() method
  
// Import the filesystem module
const fs = require('fs');
  
// Start watching the file
fs.watchFile("example_file.txt", (curr, prev) => {
  console.log("\nThe file was edited");
  
  console.log("Previous Modified Time:", prev.mtime);
  console.log("Current Modified Time:", curr.mtime);
});
  
// Make Changes to the file before 
// it has been stopped watching
setTimeout(
  () => fs.writeFileSync("example_file.txt",
         "File Contents are Edited"),
  1000
);
  
// Stop watching the file
setTimeout(() => {
  fs.unwatchFile("example_file.txt");
  console.log("\n> File has been stopped watching");
}, 6000);
  
// Make Changes to the file after
// it has been stopped watching
setTimeout(
  () => fs.writeFileSync("example_file.txt",
          "File Contents are Edited Again"),
  7000
);

输出:

The file was edited
Previous Modified Time: 2020-05-30T08:43:28.216Z
Current Modified Time: 2020-05-30T08:43:37.208Z

File has been stopped watching

示例 2:

// Node.js program to demonstrate 
// the fs.unwatchFile() method
  
// Import the filesystem module
const fs = require('fs');
  
// Defining 2 listeners for watching the file
let listener1 = (curr, prev) => {
  console.log("Listener 1: File Modified");
};
let listener2 = (curr, prev) => {
  console.log("Listener 2: File Modified");
};
  
// Using both the listeners on one file
fs.watchFile("example_file.txt", listener1);
fs.watchFile("example_file.txt", listener2);
  
// Modify the file contents
setTimeout(
  () => fs.writeFileSync("example_file.txt",
          "File Contents are Edited"),
  1000
);
  
// Stop using the first listener
setTimeout(() => {
  fs.unwatchFile("example_file.txt", listener1);
  console.log("\n> Listener 1 has been stopped!\n");
}, 6000);
  
// Modify the file contents again
setTimeout(
  () => fs.writeFileSync("example_file.txt",
          "File Contents are Edited Again"),
  8000
);

输出:

Listener 1: File Modified
Listener 2: File Modified

Listener 1 has been stopped!

Listener 2: File Modified

参考: https://nodejs.org/api/fs.html#fs_fs_unwatchfile_filename_listener