如何知道非阻塞递归作业在nodejs中完成

时间:2015-03-07 14:12:25

标签: node.js recursion nonblocking

我已经编写了这个非阻塞nodejs样本递归文件搜索代码,问题是我无法弄清楚任务何时完成。喜欢计算任务所需的时间。

fs = require('fs');

searchApp = function() {

    var dirToScan = 'D:/';

    var stringToSearch = 'test';

    var scan = function(dir, done) {
        fs.readdir(dir, function(err, files) {
            files.forEach(function (file) {
                var abPath = dir + '/' + file;
                try {
                    fs.lstat(abPath, function(err, stat) {
                        if(!err && stat.isDirectory()) {
                            scan(abPath, done);;
                        }
                    });
                }
                catch (e) {
                    console.log(abPath);
                    console.log(e);
                }

                matchString(file,abPath);
            });
        });
    }

    var matchString = function (fileName, fullPath) {
        if(fileName.indexOf(stringToSearch) != -1) {
            console.log(fullPath);
        }
    }

    var onComplte = function () {
        console.log('Task is completed');
    }

    scan(dirToScan,onComplte);
}


searchApp();

上面的代码完美地进行了搜索,但我无法弄清楚递归何时结束。

1 个答案:

答案 0 :(得分:0)

不是那么直截了当,我猜你必须依靠计时器和承诺。

fs = require('fs');
var Q = require('q');
searchApp = function() {

    var dirToScan = 'D:/';    
    var stringToSearch = 'test';
    var promises = [ ];
    var traverseWait = 0;

    var onTraverseComplete = function() {
      Q.allSettled(promises).then(function(){
       console.log('Task is completed');
      });
    }

    var waitForTraverse = function(){
      if(traverseWait){
        clearTimeout(traverseWait);
      } 
      traverseWait = setTimeout(onTraverseComplete, 5000);  
    }

    var scan = function(dir) {
        fs.readdir(dir, function(err, files) {
            files.forEach(function (file) {
                var abPath = dir + '/' + file;
                var future = Q.defer();
                try {
                    fs.lstat(abPath, function(err, stat) {
                        if(!err && stat.isDirectory()) {
                            scan(abPath);                                
                        }
                    });
                }
                catch (e) {
                    console.log(abPath);
                    console.log(e);
                }

                matchString(file,abPath);
                future.resolve(abPath);
                promises.push(future);
                waitForTraverse();
            });
        });
    }

    var matchString = function (fileName, fullPath) {
        if(fileName.indexOf(stringToSearch) != -1) {
            console.log(fullPath);
        }
    }



    scan(dirToScan);
}



searchApp();