1

I wanted to see what filename would be returned when I pass the argument __filename to the node binary. In result I was expecting to see the node binary's path which would be evaluating the command but I got the following result:

node -p __filename
[eval]

What is [eval]? How do I interpret it?

My node version is as follows:

node --version
v14.17.4
Srikanth Suresh
  • 83
  • 1
  • 2
  • 8
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval – Marc Sep 25 '21 at 10:45
  • Why should an eval object be a __filename? – Srikanth Suresh Sep 26 '21 at 05:37
  • Because you are in REPL. What else sould be `__filename` set to? Same for `__dirname`, that is set to `.` Should it be undefined? That would break things. – Marc Sep 26 '21 at 08:03
  • Let us have a look at the __filename documentation at https://nodejs.org/api/modules.html#modules_filename . It is supposed to be "The file name of the current module. This is the current module file's absolute path with symlinks resolved." so if [eval] is the module performing the REPL we should be expecting its file path. – Srikanth Suresh Sep 26 '21 at 08:29
  • Eval is not a file/module, its a built in js function. Therefore it has no filename/path. Its just a mocking, so you dont break things. – Marc Sep 26 '21 at 09:02
  • 1
    The expected output is the absolute path of the module and not a function name. – Srikanth Suresh Sep 26 '21 at 10:26

1 Answers1

0

See https://nodejs.org/api/modules.html#__filename

You should use it in your script

script.js:

console.log(__filename);

then run:

node script.js

It will print actual full name of script.

When one does

node -p 'console.log(__filename)'
[eval]
undefined

The __filename cannot be defined, as there is not script file. Maybe node.js has eval() functions that, that get the filename value. But in some case it fails, or is not called.

Also see Why is __dirname not defined in node REPL?

Paul Verest
  • 60,022
  • 51
  • 208
  • 332