This should be a fairly simple one to answer I would hope, however it's got me stumped - maybe I've been staring at too much code today!
I am trying to do a simple if statement which checks to see if a folder exists. If the folder doesn't exist, make it, if it does, delete the content.
The problem I am having is that if the directory doesn't exist, then the callback (stats) is undefined. With fs.exist it would be quite simple, but since its deprecated, I wanted to ensure this was future proofed.
var seriesid = 5;
fs.stat("temp/" + seriesid, function (err, stats){
if(!stats.isDirectory()){
fs.mkdir("temp/" + seriesid);
console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
callback();
}
else if (err != 'ENOENT') {
callback(err);
}
else {
// TODO: Folder exists, delete contents
console.log('Does exist');
callback();
}
});
Any help on how to accomplish this would be appreciated
The simplest way to check if a certain directory exists in Node. js is by using the fs. existsSync() method. The existsSync() method asynchronously checks for the existence of the given directory.
The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method. The existsSync method will return true if the file exists and else it'll return false.
Synchronously tests whether or not the given path exists by checking with the file system.
The existsSync method of the fs module is used to check if a file or directory exists in the file system.
Check err
first. Then check isDirectory()
fs.stat("temp/" + seriesid, function (err, stats){
if (err) {
// Directory doesn't exist or something.
console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
return fs.mkdir("temp/" + seriesid, callback);
}
if (!stats.isDirectory()) {
// This isn't a directory!
callback(new Error('temp is not a directory!'));
} else {
console.log('Does exist');
callback();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With