PhilPhil
PhilPhil

Reputation: 173

How to get absolute path of a javascript?

I'm trying to find the absolute path of my javascript file (not the URL). Instead of hardcoding absolutely paths, I'd prefer using relative paths. For example:

/static/js/index.js
/static/config/1.json
/static/config/2.json

If I can get the absolute path of index.js, then I'm only ../config/ away from accessing either of the two json files.

Searching SO and the internet I either get suggestions for finding the URL, which work but won't solve my problem. Or for file paths, using windows.location.pathname but any permutation of it that I try either returns an empty string, or /.

        var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/');
        console.log("Curr dir: " + currentDirectory);

(Returns empty string)

        var location = window.location.pathname;
        var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
        console.log(" dirPath: " + directoryPath);

(Returns a /)

What I'm hoping for is something like:

var absolute_path = window.function.absolute.path()

Which would return say: /u/user/develop/project/server/static/js/index.js From which I could: (pseudo code again)

var locations = absolute_path.split("js");
# location[0] = "/u/user/develop/project/server/static"
# location[1] = "js/index.js"
var config_file_locations = locations[0] + "config/";
var absolute_path_json1 = config_file_locations + "1.json"

-- EDIT --

Ok, looking at window.location it returns the URL so clearly that's not an answer here.

Upvotes: 2

Views: 6956

Answers (1)

Quentin
Quentin

Reputation: 944442

/static/js/index.js is an absolute path. You can tell because it starts with a /, which takes it back to the root of the web site.

There is no automatic way for a browser to tell anything about how a web server determined how it generated the content for a given URL.

All a browser knows is that it asked the server for /static/js/index.js and the server responded with some JavaScript.

The server might have read a static file, and that file might be in a directory called js and that directory might be a subdirectory of one called static … but then the server might have taken the whole URL, used it in a database query, and pulled the results from a database … or it might have proxied the request to another HTTP server on another computer on another continent.

If you want your client-side JS to know anything about the structure of the filesystem on the HTTP server, then you need to give it that information somehow. It can't get it from the browser.

Upvotes: 1

Related Questions