当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js fs.unwatchFile()用法及代码示例


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

用法:

fs.unwatchFile(filename[, listener])

参数:该方法接受上述和以下所述的两个参数:

  • filename:它是一个String,Buffer或URL,表示必须停止监视的文件。
  • listener:该函数指定以前使用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




相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | fs.unwatchFile() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。