Search code examples
javascriptintrospectionecmascript-5

Retrieve the current javascript file name and line number


Is there a standard way of accessing the current file name of a script?

Is there something like __FILE__ and __LINE__ in C++ or PHP.

If there is no standard way of doing this, what are the tools that would allow to add such functionality to .js files (preprocessing)?

I am not looking for browser specific solutions (i.e. ReferenceError: document is not defined)


Solution

  • I'm not sure what you're using, but in node.js you can do it like this

    file.js

    var path = require("path");
    console.log(path.basename(__filename));
    // => file.js
    

    There's no way to do this in the browser though.