You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 addedFiles array: 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 with watcher.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 addedFiles array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:33:22