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
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js GM paint()用法及代碼示例
- Node.js GM drawRectangle()用法及代碼示例
- Node.js GM whiteThreshold()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
- Node.js GM spread()用法及代碼示例
- Node.js GM drawBezier()用法及代碼示例
- Node.js GM orderedDither()用法及代碼示例
- Node.js GM quality()用法及代碼示例
- Node.js GM raise()用法及代碼示例
- Node.js GM resize()用法及代碼示例
- Node.js GM segment()用法及代碼示例
- Node.js GM threshold()用法及代碼示例
- Node.js GM roll()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.unwatchFile() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。