@@ -4,6 +4,7 @@ var fs = require('fs');
44var sysPath = require ( 'path' ) ;
55var readdirp = require ( 'readdirp' ) ;
66var isBinaryPath = require ( 'is-binary-path' ) ;
7+ var debounce = require ( 'lodash.debounce' ) ;
78
89// fs.watch helpers
910
@@ -341,15 +342,12 @@ function(dir, stats, initialAdd, depth, target, wh, callback) {
341342 parentDir . add ( sysPath . basename ( dir ) ) ;
342343 this . _getWatchedDir ( dir ) ;
343344
345+ var debouncedRead ;
346+
344347 var read = function ( directory , initialAdd , done ) {
345348 // Normalize the directory name on Windows
346349 directory = sysPath . join ( directory , '' ) ;
347350
348- if ( ! wh . hasGlob ) {
349- var throttler = this . _throttle ( 'readdir' , directory , 1000 ) ;
350- if ( ! throttler ) return ;
351- }
352-
353351 var previous = this . _getWatchedDir ( wh . path ) ;
354352 var current = [ ] ;
355353
@@ -380,9 +378,11 @@ function(dir, stats, initialAdd, depth, target, wh, callback) {
380378 this . _addToNodeFs ( path , initialAdd , wh , depth + 1 ) ;
381379 }
382380 } . bind ( this ) ) . on ( 'end' , function ( ) {
383- if ( throttler ) throttler . clear ( ) ;
384381 if ( done ) done ( ) ;
385382
383+ // Run any pending reads that may be queued
384+ debouncedRead . flush ( ) ;
385+
386386 // Files that absent in current directory snapshot
387387 // but present in previous emit `remove` event
388388 // and are removed from @watched [directory].
@@ -401,20 +401,35 @@ function(dir, stats, initialAdd, depth, target, wh, callback) {
401401 } . bind ( this ) ) . on ( 'error' , this . _handleError . bind ( this ) ) ;
402402 } . bind ( this ) ;
403403
404+ // Create a debounced version of read
405+ debouncedRead = debounce ( read , 1000 , {
406+ leading : true ,
407+ trailing : true ,
408+ maxWait : 1000
409+ } ) ;
410+
404411 var closer ;
405412
406413 if ( this . options . depth == null || depth <= this . options . depth ) {
407414 if ( ! target ) read ( dir , initialAdd , callback ) ;
408415 closer = this . _watchWithNodeFs ( dir , function ( dirPath , stats ) {
409416 // if current directory is removed, do nothing
410417 if ( stats && stats . mtime . getTime ( ) === 0 ) return ;
411-
412- read ( dirPath , false ) ;
418+ debouncedRead ( dirPath , false ) ;
413419 } ) ;
414420 } else {
415421 callback ( ) ;
416422 }
417- return closer ;
423+
424+ // Close function that calls fs closer and cancels any pending debounced reads
425+ return function ( ) {
426+ if ( closer ) {
427+ closer ( ) ;
428+ }
429+
430+ // Cancel any pending reads that may be queued
431+ debouncedRead . cancel ( ) ;
432+ } ;
418433} ;
419434
420435// Private method: Handle added file, directory, or glob pattern.
0 commit comments