__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 · Tags: javascript, ruby, spidermonkey

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.


Current Projects

jQuery JavaScript Library

jQuery

Comprehensive DOM, Event, Animation, and Ajax JavaScript Library.

Recent Projects

Pro JavaScript Techniques

JavaScript Book

The best techniques for professional JavaScript. Published by Apress.


Hosting provided by the cool dudes at Engine Yard.