在 Node.JS 中可以使用 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<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("文件不存在")
- }
- })
效果图:
来源: http://www.css88.com/qa/node-js/10556.html