How to check if a path is file or directory?
Information about a file or directory can be retrieved asynchronously using fs.stat() or fs.lsstat()
fs.stat(path,callback) . The callback takes 2 arguments (err,stats) . The stats is fs.Stats object. It has methods for checking file or directory.
fs.stat(filePath, function (err, stats) {
if (err) {
console.log("Error");
process.exit(1);
}
else {
if(stats.isDirectory())
console.log(filePath + " is a directory");
else if(stats.isFile())
console.log(filePath + " is a file");
else {
// optionally check for BlockDevice, CharacterDevice etc
console.log(filePath + " is not a file or directory");
}
}
});
The synchronous versions for stat/lsstat are fs.statSync() and fs.lsstatSync()