node.js 简单的异步文件遍历函数

1,引用node的fs和path模块

var fs = require("fs");
var path = require("path");

2,思路:

a,利用readdir读取所有子目录名

b,读取完成进行回调,先检查第一项,利用path.join()得到当前的目录/文件名

c,利用fs.stat()检测当前项是目录还是文件夹,是文件夹,以当前目录执行递归;是文件,检查第二项

d,当一个目录中的所有项都被遍历后,返回上级目录,开始遍历上级目录的下一项。

e,遍历完成:输出遍历完成。

function travel(dir,callback,finish){
    fs.readdir(dir,function(err,file){
        (function next(i){
            if(i<file.length){
                var pathname = path.join(dir,file[i]);

                fs.stat(pathname,function(err,stats){
                    if(stats.isDirectory()){
                        travel(pathname,callback,function(){
                            next(i+1);
                        })
                    }
                    else{
                        callback(pathname,function(){
                            next(i+1);
                        })
                    }
                })
            }
            else{
                finish();
            }
        })(0)
    })
}


travel("../",function(pathname,func){
    console.log(pathname);
    func();
},function(){
    console.log("遍历完成");
});

猜你喜欢

转载自my.oschina.net/u/3400107/blog/1589898
今日推荐