25

I want to check if a file exists locally, where the HTML file is located. It has to be JavaScript. JavaScript will never be disabled. jQuery is not good but can do.

By the way, I am making a titanium app for Mac so I am looking for a way of protecting my files from people who click "show package contents".

6
  • By "locally," do you mean on the client machine? That is, the one with the browser. If so, the answer is no — you have no file access. But it's not clear what you mean.
    – harpo
    Feb 25, 2011 at 8:39
  • 2
    Do you understand how horrifically insecure this is?
    – rook
    Feb 25, 2011 at 18:49
  • i'm doing this all my computer so it's not going on a server. Feb 26, 2011 at 0:17
  • anyway, pretend that the file was located in "assets/index.html" I want to check if a file exists in assets. Feb 26, 2011 at 0:18
  • Use ajax, see my answer here: stackoverflow.com/a/14691735/1981050 Feb 4, 2013 at 17:24

9 Answers 9

14

Your question is ambiguous, so there are multiple possible answers depending on what you're really trying to achieve.

If you're developping as I'm guessing a desktop application using Titanium, then you can use the FileSystem module's getFile to get the file object, then check if it exists using the exists method.

Here's an example taken from the Appcelerator website:

var homeDir = Titanium.Filesystem.getUserDirectory();
var mySampleFile = Titanium.Filesystem.getFile(homeDir, 'sample.txt');

if (mySampleFile.exists()) {
    alert('A file called sample.txt already exists in your home directory.');
    ...
}

Check the getFile method reference documentation

And the exists method reference documentation

For those who thought that he was asking about an usual Web development situation, then thse are the two answers I'd have given:

1) you want to check if a server-side file exists. In this case you can use an ajax request try and get the file and react upon the received answer. Although, be aware that you can only check for files that are exposed by your web server. A better approach would be to write a server-side script (e.g., php) that would do the check for you, given a filename and call that script via ajax. Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.

2) you want to check if a client-side file exists. In this case, as pointed you by others, it is not allowed for security reasons (although IE allowed this in the past via ActiveX and the Scripting.FileSystemObject class) and it's fine like that (nobody wants you to be able to go through their files), so forget about this.

13

Since 'Kranu' helpfully advises 'The only interaction with the filesystem is with loading js files . . .', that suggests doing so with error checking would at least tell you if the file does not exist - which may be sufficient for your purposes?

From a local machine, you can check whether a file does not exist by attempting to load it as an external script then checking for an error. For example:

<span>File exists? </span>
<SCRIPT>
    function get_error(x){
        document.getElementsByTagName('span')[0].innerHTML+=x+" does not exist.";
    }
    url="   (put your path/file name in here)    ";
    url+="?"+new Date().getTime()+Math.floor(Math.random()*1000000);
    var el=document.createElement('script');
    el.id="123";
    el.onerror=function(){if(el.onerror)get_error(this.id)}
    el.src=url;
    document.body.appendChild(el);
</SCRIPT>

Some notes...

  • append some random data to the file name (url+="?"+new Date etc) so that the browser cache doesn't serve an old result.
  • set a unique element id (el.id=) if you're using this in a loop, so that the get_error function can reference the correct item.
  • setting the onerror (el.onerror=function) line is a tad complex because one needs it to call the get_error function AND pass el.id - if just a normal reference to the function (eg: el.onerror=get_error) were set, then no el.id parameter could be passed.
  • remember that this only checks if a file does not exist.
3
  • Many thanks for taking the time to reply, and my reason for posting this solution was for others following this thread in search of an answer. I'm frankly puzzled by those who, as in this thread, contribute the 'it can't be done' line, as this appears to be of zero value.
    – Siubear
    May 10, 2011 at 4:29
  • So the error event isn't triggered until you append the element to the document? One could append it "out of sight", I suppose, but it would be even better not having to append it at all, if that's possible. Jan 15, 2014 at 13:49
  • I tried this on Firefox, with: url="c:\\Windows\\Web\\js.js";, and it always returns 123 does not exist., regardless of whether the file exists or not. I also tried: url="file://c:\\Windows\\Web\\js.js"; with the same results. Nov 20, 2016 at 14:19
9

You can use this

function LinkCheck(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
5
  • 1
    How can you use this for checking existence of a file? Jan 29, 2016 at 9:17
  • 1
    @ChetanPurohit - You would call it like this: var x=LinkCheck("c:\\Windows\\Web\\Wallpaper\\img1.jpg");. Then test the value of x: x ? alert("File Exists") : alert("File Doesn't exist") ; or if (x){ alert("File Exists"); } else { alert("File Doesn't exist"); }. Unfortunately, I tried this on my system and it fails after the line: http.open('HEAD', url, false); Nov 20, 2016 at 13:56
  • @ChetanPurohit - I also tried var x=LinkCheck("file://c:\\Windows\\Web\\Wallpaper\\img1.jpg");, and this fails after: http.send();. In both cases, the "failure" is that it doesn't return from the call to LinkCheck(). Nov 20, 2016 at 14:26
  • Thank you for replying @Kevin Nov 21, 2016 at 11:47
  • In the open statement shown above, false indicates "synchronous" operation. I just ran across this: Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience. Using XMLHttpRequest Nov 19, 2017 at 14:41
5

Javascript cannot access the filesystem and check for existence. The only interaction with the filesystem is with loading js files and images (png/gif/etc).

Javascript is not the task for this

3

Fortunately, it's not possible (for security reasons) to access client-side filesystem with standard JS. Some proprietary solutions exist though (like Microsoft's IE-only ActiveX component).

3

If you want to check if file exists using javascript then no, as far as I know, javascript has no access to file system due to security reasons.. But as for me it is not clear enough what are you trying to do..

1

An alternative: you can use a "hidden" applet element which implements this exist-check using a privileged action object and override your run method by:

File file = new File(yourPath);
return file.exists();
1
  • 1
    What is a >"hidden" applet element?
    – clankill3r
    Jul 22, 2020 at 12:05
1

No need for an external library if you use Nodejs all you need to do is import the file system module. feel free to edit the code below: const fs = require('fs')

const path = './file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file exists
})
0

One way I've found to do this is to create an img tag and set the src attribute to the file you are looking for. The onload or onerror of the img element will fire based on whether the file exists. You can't load any data using this method, but you can determine if a particular file exists or not.

2
  • 2
    I just tried this approch. The error handler is called when loading non-image-types. So its not possible to determine if the file exists or not!
    – Fuzzyma
    Aug 2, 2016 at 23:33
  • 4
    If it's "a way you found to do this" and others say it's not working, I'd say you should share your code so that we can see how exactly you implemented this
    – YakovL
    Aug 2, 2016 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.