fs.exists(path,callback)来检查目录文件是否存在,
    var fs=require(“fs”);
    
    fs.exists(“../7”,function(exists){
    
    
    if(exists){
    
    
    console.log(“文件存在”)
    
    }
    
    if(!exists){
    
    
    console.log(“文件不存在”)
    
    }
    
    })
   
    
   
7这个文件夹下有多少个文件,查看每个文件的绝对路径
    var fs=require(“fs”);
    
    var p=require(“path”);
    
    var path=”;
    
    fs.exists(“../7”,function(exists){
    
    
    if(exists){
    
    
    fs.readdir(‘../7’,function(err,files){
    
    
    if(err){
    
    
    console.log(“读取文件夹下7文件失败”);
    
    }else{
    
    
    console.log(“7文件夹下有”+files.length+”个文件”);
    
    for(var i=0;i<files.length;i++){
    
    
    path=p.resolve(__dirname,’../7′)+p.sep
    
    path=path+files[i];
    
    console.log(“—-“+path)
    
    fs.stat(path,function(err,stat){
    
    
    if(err){
    
    
    console.log(“查看文件夹7下的文件信息失败”);
    
    }else{
    
    
    if(stat.isFile()){
    
    
    fs.realpath(path,function(err,resolvePath){
    
    
    if(err){
    
    
    throw err;
    
    //console.log(“查看文件绝对路径失败”);
    
    }else{
    
    
    console.log(“文件的路径为”+resolvePath)
    
    }
})
    }
    
    }
    
    })
    
    }
    
    }
    
    })
    
    }
    
    if(!exists){
    
    
    console.log(“文件不存在”)
    
    }
    
    })
   
得到的结果为下图,我们发现得到的绝对路径有问题,原因是回调函数还没有反回来呢,你的for循环又开始往下执行了,吧这个文件path更改了。改成同步试一下
    
   
    var fs=require(“fs”);
    
    var p=require(“path”);
    
    var path=”;
    
    fs.exists(“../7”,function(exists){
    
    
    if(exists){
    
    
    fs.readdir(‘../7’,function(err,files){
    
    
    if(err){
    
    
    console.log(“读取文件夹下7文件失败”);
    
    }else{
    
    
    console.log(“7文件夹下有”+files.length+”个文件”);
    
    for(var i=0;i<files.length;i++){
    
    
    path=p.resolve(__dirname,’../7′)+p.sep
    
    path=path+files[i];
    
    console.log(“—-“+path)
    var stat=fs.statSync(path);
    
    if(stat.isFile()){
    
    
    var resolvePath=fs.realpathSync(path);
    
    console.log(“文件的路径为”+resolvePath);
    }
    
    }
    
    }
    
    })
    
    }
    
    if(!exists){
    
    
    console.log(“文件不存在”)
    
    }
    
    })
   
运行结果:
    
    
   
 
