在nodejs中可以使用fs.exists()方法来检查目录文件是否存在;该方法测试某个路径下的文件是否存在。由于该方法属于fs模块,使用前需要引入fs模块(var fs=require("fs")。
语法:fs.exists(path,callback)
参数:
● path:判断的文件夹、文件的路径。
● callback:回调函数。
示例: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
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("文件不存在")
}
})
效果图: