Skip to content

Instantly share code, notes, and snippets.

@adamasantares
Last active May 16, 2021 13:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamasantares/04cf84e3a99326a4d73f to your computer and use it in GitHub Desktop.
Save adamasantares/04cf84e3a99326a4d73f to your computer and use it in GitHub Desktop.
__FILE__ and __DIR__ in JavaScript
/**
* __DIR__ & __FILE__ for JavaScript (was tested in IE 7-10)
* This definition must be inserted at root of script file, outside of any function.
*/
(function(w,d){
var u=null;
w.__FILE__=(function(){
try{u();}catch(err){
if(err.stack){
u=(/(http[s]?:\/\/.*):\d+:\d+/m).exec(err.stack);
if(u&&u.length>1){ return u[1]; }
}
u = (d.scripts.length>0) ? d.scripts[d.scripts.length-1].src : "";
if (u.length > 0 && u.indexOf("://") < 0 && u.substring(0,1) != "/" ){
u = location.protocol + "//" + location.host + "/" + u;
}
return u;
}
})();
w.__DIR__=(function(f){
f=(/^(.*\/)[a-z0-9 -_]+\.[a-z]+$/i).exec(f);
return (f&&f.length>1)?f[1]:"";
})(w.__FILE__);
})(window, document);
console.log(__FILE__);
console.log(__DIR__);
/**
* __DIR__ & __FILE__ for JavaScript (was tested in IE 7-10)
* This definition must be inserted at root of script file, outside of any function.
*/
(function(w,d){var u=null;w.__FILE__=(function(){try{u();}catch(err){if(err.stack){u=(/(http[s]?:\/\/.*):\d+:\d+/m).exec(err.stack);if(u&&u.length>1){return u[1];}}u=(d.scripts.length>0)?d.scripts[d.scripts.length-1].src:"";if(u.length>0 && u.indexOf("://")<0 && u.substring(0,1)!="/"){u=location.protocol+"//"+location.host+"/"+u;}return u;}})();w.__DIR__=(function(f){f=(/^(.*\/)[a-z0-9 -_]+\.[a-z]+$/i).exec(f);return (f&&f.length>1)?f[1]:"";})(w.__FILE__);})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment