Mr Mystery Guest Mr Mystery Guest - 4 years ago 109
Javascript Question

Determine if file exists or is 0 Bytes

In Photoshop I can read in a text file.

function does_file_exist(f)
{
var lines = "";
var aFile = new File(f);
aFile.open("r");
while(!aFile.eof)
{
var line = aFile.readln();
if (line != null && line.length >0)
{
lines += line + "\n";
}
}
aFile.close();

if (lines.length == 0)
{
alert(f + "\ndoes not exist!");
return false;
}
else
{
var trunc = lines.substring(0,256);
alert(f + " exists!\nHere's proof:\n\n" + trunc + "...")
return lines;
}
}


If the string returned has a length of 0 we assume that the file simply doesn't exist. This works fine, but what happens if there is an empty file of 0 bytes? Can I access the filesize properties? Or is there another way around this problem? There seem to be problems with file.exists()

Answer Source
File(f).exists

Is a Boolean not a function

Boolean exists Read only Property
If true, this object refers to a file or file-system alias that actually exists in the file system.

Update: Actually "Mr. Mystery Guest" is right (see comments).

File('~/Desktop/does-not-exist.txt').exists

returns true for me on macOS 10.12.2 and PS CC2017 even though the file does not exists. Using

new File('~/Desktop/does-not-exist.txt').exists

seems to work as excepted.

Update 2:

This error seems to be a Photoshop specific problem. In ESTK and in InDesign File('~/Desktop/does-not-exist.txt').exists returns false

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download