File - Folder
How to check if a file is already open
The Adobe JavaScript documentation has the following warning around opening files:
NOTE: Be careful about opening a file more than once. The operating system usually permits you to do so, but if you start writing to the file using two different File objects, you can destroy your data.
To tell if a File object is already open we can use the tell() method
Retrieves the current position as a byte offset from the start of the file.
Returns a number, the position index.
For an open file It returns: 0 (for new or empty file), or any number. If the file is not open, it returns -1.
main(); function main() { var file = new File("~/Desktop/Log.txt"); if (file.exists) { file.open("e"); file.seek(0, 2); } else { file.open("w"); } var tell = file.tell(); // 0 for new or empty file; any number for existing file file.write("Test"); file.close(); tell = file.tell(); // -1 the file is closed }
How to get the cache folder for both mac and windows?
app.generalPreferences.temporaryFolder.parent
With my German InDesign 2020 on Windows 10 it returns:
~/AppData/Local/Adobe/InDesign/Version%2015.0/de_DE/Caches
How to get file extension in JS:
var myString = "this.is.my.file.txt" alert(myString.substring(myString.lastIndexOf(".")+1))
Get the file path to a file located in the same folder as the active script:
var csvFileName = "Change fonts list.csv"; function GetCsv() { var scriptFile = GetActiveScript(); var scriptFolderPath = decodeURI(scriptFile.path) + "/"; var csvFilePath = scriptFolderPath + csvFileName; var csvFile = new File(csvFilePath); if (csvFile.exists) { return csvFile; } else { return null; } }
ExtendScript Oddity with File/Folder on Mac OS X
Sort file names function for Mac (workaround for a Mac OSx bug)
See also Functions for File & Folder