本文介绍在 Node.js 中如何利用 fs 模块的 stat 方法判断指定路径是文件还是文件夹。通过示例代码展示如何获取文件状态对象,并使用 stat.isFile() 和 stat.isDirectory() 方法进行类型区分,同时包含基本的错误处理逻辑。
Node.js 判断文件类型实现
具体实现代码如下所示:
var fs = require("fs");
//判断打开的是文件 还是 文件夹
var path = "wen.txt";
fs.stat(path,function(err,stat){
if (err) {
console.error(err);
throw err;
}
console.log(stat);
console.info(path+"是一个"+stat.isFile());
console.info(path+"是一个"+stat.isDirectory());
});
console.info("打开文件成功··");

以上就是利用 Node.js 判断文件与文件夹的完整示例,供读者参考。