初步学习Node,在做一个关于文件的读取时,判断各个文件的类型是否是一个文件目录时一直报错Cannot read property 'isDirectory' of undefined,然后我试了一下使用isFile,也报错说undefined
相关代码
function file(i) {
var filename = filesarry[i];
fs.stat(__dirname + "/" + filesarry[i], function(err, stat) {
stats[i] = stat;
if (stat.isDirectory()) {
console.log(" " + i + " \033[36m" + filesarry[i] + "/\033[39m");
} else {
console.log(" " + i + " \033[90m" + filename + "/\033[39m");
}
i++;
if (i == filesarry.length) {
read();
} else {
file(i);
}
});
}
输出结果:
C:\Users\DZY\Desktop\Node学习笔记\项目实践\file-explorer\index.js:28
if (stat.isDirectory()) {
^
TypeError: Cannot read property 'isDirectory' of undefined
at C:\Users\DZY\Desktop\Node学习笔记\项目实践\file-explorer\index.js:28:14
at FSReqWrap.oncomplete (fs.js:152:21)
有可能是抛出异常了,但是你没有捕获异常,所以
stat
值是 undefined。你查看一下 err 的值是什么就知道了