NodeJS fs Stats.isFile() not defined
12,168
You are not exiting your function after encountering an error.
fs.stat(dir + "/" + file, function (err, stats) {
if (err) {
console.log(err);
return; // exit here since stats will be undefined
}
if (stats.isFile()) {
calback(dir + "/" + file);
}
if (stats.isDirectory()) {
walk(file, calback);
}
});
Related videos on Youtube
Author by
Lukas Matejka
Updated on July 12, 2022Comments
-
Lukas Matejka almost 2 years
I'm new to NodeJS and I#m trying to read a directory recursively this is my code
var fs = require('fs'); var readDir = function (dir, calback) { fs.readdir(dir, function (err, files) { if (err) console.log(err); for (var file in files) { fs.stat(dir + "/" + file, function (err, stats) { if (err) console.log(err); if (stats.isFile()) { calback(dir + "/" + file); } if (stats.isDirectory()) { walk(file, calback); } }); } }); };
This is my ErrorMessage
C:\Users\Lukas\Desktop\Enide-Studio-05-kepler-win32\ws\PlayerTest\hello-world-server.js:24 if (fs.stats.isFile()) { ^ TypeError: Cannot call method 'isFile' of undefined at C:\Users\Lukas\Desktop\Enide-Studio-05-kepler-win32\ws\PlayerTest\hello-world-server.js:24:30 at Object.oncomplete (fs.js:107:15)
What is my mistake??
-
barry-johnson over 10 years+1 for correct answer. One could also write
return console.log()
as well, since returning nothing is functionally equivalent toreturn undefined
and the result of console.log isundefined
. I would also add that some consider it a good practice toreturn callback(...)
as well. It sometimes save the need of an else block, etc.