Skip to content

Instantly share code, notes, and snippets.

@plepe
Created October 15, 2012 11:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save plepe/3891980 to your computer and use it in GitHub Desktop.
Save plepe/3891980 to your computer and use it in GitHub Desktop.
__FILE__ in JavaScript
/***
* This gist provides a __FILE__ variable, which holds the path to the file
* from which the currently running source is being executed.
*
* Usage example: alert(__FILE__);
*
* Thanks to http://ejohn.org/blog/__file__-in-javascript/ on which this gist
* is based on.
*
* Tested in Mozilla Firefox 9, Mozilla Firefox 16, Opera 12, Chromium 18
*/
(function(){
this.__defineGetter__("__FILE__", function() {
var stack=((new Error).stack).split("\n");
if(stack[0]=="Error") { // Chromium
var m;
if(m=stack[2].match(/\((.*):[0-9]+:[0-9]+\)/))
return m[1];
}
else { // Firefox, Opera
return stack[1].split("@")[1].split(":").slice(0,-1).join(":");
}
});
})();
@BR0kEN-
Copy link

BR0kEN- commented Jan 25, 2014

Simplified and shortened code: https://gist.github.com/BR0kEN-/8620537

@yashaka
Copy link

yashaka commented Mar 13, 2023

One more version for nodejs, that will also not fail in REPL:

(function(){
  Object.defineProperty(globalThis, '__FILE__', { get() {
    return (new Error).stack.split('at file://')?.at(1)?.split(':')?.at(0)
  }})
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment