5

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)

Community
  • 1
  • 1
Coyote
  • 2,343
  • 25
  • 46
  • 1
    No, there is no standard way to do this, as it's mainly condsidered useless, and when you need the filename of the current file in your code, 99% of the time you're doing something wrong. – adeneo Jan 02 '14 at 02:37
  • 1
    I don't know of any way to do that inside javascript, but it would be easy to implement by injecting a variable server side – norlesh Jan 02 '14 at 02:39

3 Answers3

4

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.

maček
  • 73,409
  • 36
  • 162
  • 195
  • Most of the time the scripts are used outside of node.js, but I can run most tests in node and benefit from this. Thank you! – Coyote Jan 02 '14 at 02:47
2

If you're using NodeJS you can use __filename or module.filename, however in the browser, no you can't.

OneOfOne
  • 88,915
  • 19
  • 172
  • 173
-2

Yep there is __FILE__ in php. You can use basename(__FILE__, ".php") to have the file name and cut off the extension if you want.

user3152069
  • 412
  • 3
  • 9