Skip to main content
Inspiring
January 6, 2016
Answered

How to check if a file is already open

  • January 6, 2016
  • 1 reply
  • 1355 views

My question is about the local file system object `File`. I am writing a function that reads the contents of a text file. The function is passed a `File` object as an argument and then reads the content before some other logic.

Before you can read a `File` object it needs to be 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.

So my question is... How do I tell if a File object is already open? There doesn't appear to be a property or method that simply tells me this.

This topic has been closed for replies.
Correct answer Jump_Over

Hi,

Suggest to use method file.tell() ==> which returns "-1" if current position cant be retrieved.

If file is opened it returns number >=0 .

Jarek

1 reply

TᴀW
Legend
January 6, 2016

Just a thought: Perhaps you can try reading from the file first without opening it. If this fails, it's closed. If it succeeds, that would mean it's already open.

I do not know if this approach works though -- haven't tested it.

Visit www.id-extras.com for powerful InDesign scripts that save hours of work — automation, batch tools, and workflow boosters for serious designers.
McShamanAuthor
Inspiring
January 6, 2016

Well something like this seems to work. But it seems a little hacky:

function fileIsOpen(fl) {

  fl.error = '';

  fl.readch();

  if(fl.error) {

  return false;

  } else {

  return true;

  }

}

Jump_Over
Jump_OverCorrect answer
Legend
January 6, 2016

Hi,

Suggest to use method file.tell() ==> which returns "-1" if current position cant be retrieved.

If file is opened it returns number >=0 .

Jarek