views:

145

answers:

3

Hi everyone! How to use javascript to determine whether a file exists in a directory?

A: 

I don't know if there's an elegant way to do this, but for a lightweight solution you could try and load the file as the src to an Image object, and handle the onerror event.

Tom Ritter
+5  A: 

If the JavaScript is running in a web browser, you do not have access to the local filesystem. If there were a way to get access to the local filesystem, it would be considered a security hole that would be fixed by the browser vendor.

Nate
does a firefox extension count as "in a web browser" ? You can access the filesystem from there.
Breton
An extension is not running *in* a web browser, it is running *as part of* a web browser.
NickFitz
+4  A: 

If it's on the server, you could make an HTTP HEAD request via Ajax, and look if the HTTP Status Code is 404 (Not found) or 200 (Ok).

An example using jQuery:

$.ajax({
  type: 'HEAD',
  url: 'somefile.ext',
  complete: function (xhr){
    if (xhr.status == 404){
      alert(xhr.statusText); // Not found
    }
  }
});
CMS
nice. never thought of this one :)
Alec Smart