0
var req = new XMLHttpRequest();  
req.open('GET', '20121209.xml', false);   
req.send(null);  
if(req.status == 0)
{ 
//file exist
}

I want to check whether file is existed or not in local machine using javascript. So I wrote the code like above. I can check when file is existed, but I cannot check when the file is not existed.

Finally I want to do something when file is not existed. Can I do this???

4
  • 2
    use the else {} after if(req.status == 0){}? because if this statement fails then it may not exist. but you can not do this in some browsers like chrome because of the security settings (accessing local files on file://...) of the browsers and how do you know if it is the right path you are looking currently? hat do you want to achieve with this? Commented Dec 9, 2012 at 11:16
  • 1
    If you want to do this from a normal web page, then no, it's not possible. Commented Dec 9, 2012 at 11:17
  • 1
    if (req.status == 404) { //doesn't exist } Also, it works only if you are executing the JS from a file:// url. If running it on HTTP you can't access the local file-system. Commented Dec 9, 2012 at 11:17
  • If there is no file, the html code is not work. Commented Dec 9, 2012 at 11:18

1 Answer 1

4

Javascript is sandboxed in the browser that is executing it, it can not access the client's local file system if the JS is served from a non-local location. Doing what you listed will make a request to

http://website.js.is.on.com/20121209.xml
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.