Here's one way to tell the difference.
var fileOrFolder = new File('/Users/bbb/Desktop/example.epr');
var type = typeof fileOrFolder;
if (fileOrFolder.commonFiles){
alert("It's a folder.");
} else {
alert("It's a file.");
}
Bruce Bullis wrote Here's one way to tell the difference. var fileOrFolder = new File('/Users/bbb/Desktop/example.epr'); var type = typeof fileOrFolder; if (fileOrFolder.commonFiles){ alert("It's a folder."); } else { alert("It's a file."); } |
Wait, what? Did you test that code?
- You have an unused variable "type" there. If the thought was to get "File" or "Folder" in the type variable, you'd need to use the constructor property: typeof returns "object".
- You are using the "new File()" approach. Using the new keyword here will always return a File object.
- Even if you were using the straight File() approach, this would not work. As I outlined in my response, the documentation does not align with actual results (at least on a mac): you need to use Folder('/path/to/test') in order to make the proper distinction.
Indeed, testing in ESTK shows that no matter what you pass to the new File() function you always get "It's a file." as output. In order to make this work, you'd have to use the following code:
var fileOrFolder = Folder('/tmp'); // Use Folder to actually get the switch.
if (fileOrFolder.constructor.commonFiles) { // BAD! HARD TO UNDERSTAND. Adding "!= undefined" would be an improvement.
alert("It's a folder.");
} else {
alert("It's a file.");
}
But, honestly, it is far more clear if you do:
var fileOrFolder = Folder('/tmp');
if (fileOrFolder.constructor == Folder) { // CHECK AGAINST CONSTRUCTOR. Better. This says "I'm verifying the type of the variable."
alert("It's a folder.");
} else {
alert("It's a file.");
}
Then again, you currently claim that something is a folder if it doesn't exist as the Folder() function will still return a Folder object even if there is nothing at the specified path. This would be even better:
var fileOrFolder = Folder('/tmp');
if (fileOrFolder.constructor == Folder) {
if (fileOrFolder.exists) // CHECK THAT THE FOLDER EXISTS.
alert("It's a folder.");
else
alert("It's nothing.");
} else {
alert("It's a file.");
}
The above code works in ESTK (on a mac, at least).
This was all covered in my original answer, and in greater depth. Is there a reason that that answer simply wasn't marked as the correct one? Am I missing something about how this should work? Or is what I wrote mac-specific?
