7

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)

2
  • 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. Commented Jan 2, 2014 at 2: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 Commented Jan 2, 2014 at 2:39

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.