I have a javascript file named main.js
.
Inside main.js
I want to get the absolute path of this current file, something like:
http://server/app/main.js http://server/app/script/main.js
What is the fastest way to get the absolute path?
Use the path. resolve() method to get an absolute path of a file from a relative path in Node. js, e.g. path. resolve('./some-file.
Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).
We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located. __filename: It returns the file name of the current module.
You can investigate script collection at:
var scripts = document.getElementsByTagName("script");
For each element in the returned scripts
array you can access its src
attribute.
The currently executing include file will always be the last one in the scripts
array. So you can access it at scripts[scripts.length-1]
.
Of course this will only work at time of initial code run and would not be useful for example within a function that is called after initial script is loaded, so if you need the value available later, you would need to save it to a variable.
Get the current pathname of the javascript file
Put this in your apache directory underneath /tmp and call it test.html. Visit the url
localhost/grader/test.html?blah=2#foobar
Javascript:
<html> <script> alert(location.pathname); // /tmp/test.html alert(location.hostname); // localhost alert(location.search); // ?blah=2 alert(document.URL); // http://localhost/tmp/test.html?blah=2#foobar alert(location.href); // http://localhost/tmp/test.html?blah=2#foobar alert(location.protocol); // http: alert(location.host); // localhost alert(location.origin); // http://localhost alert(location.hash); // #foobar </script> </html>
More information on attributes of location: http://www.w3schools.com/jsref/obj_location.asp
Or if you have jquery:
<html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> </script> <script> $(location).attr('href'); // http://localhost/tmp/test.html?blah=2#foobar $(location).attr('pathname'); // /tmp/test.html </script> </html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With