__FILE__ in JavaScript

A quick snippet that I spotted within the up-and-coming Johnson project (A Ruby/Spidermonkey hybridization.):

(function(){
  this.__defineGetter__("__FILE__", function() {
    return (new Error).stack.split("\n")[2].split("@")[1].split(":").slice(0,-1).join(":");
  });
})();

The above defines a global variable __FILE__ which, when called, returns the file name of the current JavaScript file. It’s defined using a getter in particular so that the proper file name will be determined no matter what file it’s called in (so you can safely include the above in a library file and it’ll still report the correct, current, filename).

Currently the above will only work in Spidermonkey as only it supports the .stack stacktrace Error property. If there are reasonable alternatives for WebKit or Opera (which also support __defineGetter__) let me know.

Posted: June 7th, 2008


Subscribe for email updates

7 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

John Resig Twitter Updates

@jeresig / Mastodon

Infrequent, short, updates and links.