23

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".

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
JqueryToAddNumbers
  • 1,063
  • 3
  • 14
  • 28

9 Answers9

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.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
dSebastien
  • 1,983
  • 2
  • 21
  • 31
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.
Siubear
  • 177
  • 2
  • 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 '11 at 04: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. – Per Quested Aronsson Jan 15 '14 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. – Kevin Fegan Nov 20 '16 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;
}
Jess Stone
  • 677
  • 8
  • 21
  • 1
    How can you use this for checking existence of a file? – Chetan Purohit Jan 29 '16 at 09: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);` – Kevin Fegan Nov 20 '16 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()`. – Kevin Fegan Nov 20 '16 at 14:26
  • Thank you for replying @Kevin – Chetan Purohit Nov 21 '16 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](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Types_of_requests) – Kevin Fegan Nov 19 '17 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

Kranu
  • 2,557
  • 16
  • 22
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..

Dij
  • 9,761
  • 4
  • 18
  • 35
Andrey
  • 5,906
  • 4
  • 24
  • 30
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).

John Manak
  • 13,328
  • 29
  • 78
  • 119
2

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();
Samsky
  • 438
  • 5
  • 11
1

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.

MEC
  • 11
  • 1
  • 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 02 '16 at 23:33
  • 3
    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 02 '16 at 23:34
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
})
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67