Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

In javascript/jquery, given a string of a url, how can I check if it is a url to a file or a directory?

Thanks

share|improve this question
up vote 6 down vote accepted

You can't, because there's no difference in HTTP.

A URL is neither a "file" nor a "directory." It's a resource. When requesting that resource, the server responds with, well, a response. That response consists of headers and content.

A header (such as content-disposition) may indicate that the response should be treated as a file by the consuming client. But in and of itself it's not a "file" because HTTP is not a file system.

And any resource can return any response that the server wants. For example, you might request http://www.something.com and expect not to get a file because you didn't ask for one. But it can still return one. Or, even if you ask for index.html you might not get a "file" called "index.html" but instead some other response.

Even if you ask for a "directory" from your point of view, the server is still responding with headers and content. That content may take the form of a directory listing, but it's indistinguishable from any other successful response aside from parsing the content itself.

If you're looking for something which the server has indicated is a "file" then you're looking for the content-disposition header in the response and you'll want to parse out the value of that header. Other than that one case, I'd suspect that whatever need you have to know if it's a "file" or a "directory" is a symptom of a design problem in whatever you're trying to do, since the question itself is moot in HTTP.

share|improve this answer

Like David said, you can't really tell. But if you want to find out if the last part of a url has a '.' in it (maybe that's what you mean by a "file"?), this might work:

function isFile(pathname) {
    return pathname
        .split('/').pop()
        .split('.').length > 1;
}

function isDir(pathname) { return !isFile(pathname); }

console.log(isFile(document.location.pathname));
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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