如何在Node.js中停止回调方法?Chokidar监听文件添加场景实现
Solution: Stop Chokidar 'add' Callback After 2 Files Are Added
Here's how you can modify your existing code to track added files, halt the callback once 2 files are added, and print those filenames separately:
var chokidar = require('chokidar'); var watcher = chokidar.watch('folder-name'); var log = console.log.bind(console); // Track the paths of files that get added const addedFiles = []; // Named callback function (so we can remove it later) function handleFileAdd(path) { addedFiles.push(path); log(`File ${path} has been added`); // Check if we've reached our target of 2 files if (addedFiles.length === 2) { // Stop listening to the 'add' event entirely watcher.off('add', handleFileAdd); log('\n✅ Stopped the add callback after 2 files were added'); // Print each filename individually log('\nAdded files:'); addedFiles.forEach((file, idx) => { log(`${idx + 1}. ${file}`); }); } } // Attach our callback to the watcher's 'add' event watcher.on('add', handleFileAdd);
Key Changes Explained:
- Added
addedFilesarray: This stores every file path that triggers the 'add' event, so we can track how many files have been added. - Named callback instead of arrow function: Using a named function (
handleFileAdd) lets us later remove the listener withwatcher.off(). Arrow functions can't be referenced for removal, so this is a critical adjustment. - Stop the listener at 2 files: Once the array hits exactly 2 entries, we call
watcher.off('add', handleFileAdd)to prevent the callback from running for any future file additions. - Print individual filenames: We loop through the
addedFilesarray to log each file separately, making it clear which two files triggered the stop.
If you wanted to shut down the entire watcher (not just the callback), you could add watcher.close() right after removing the listener, but your requirement specified stopping only the callback method.
内容的提问来源于stack exchange,提问作者Tamilselvan
相关产品推荐
相关产品推荐

