__dirname
and process.cwd()
are often used in the same context. Sometimes they can be used for each other, other times they can't. This can lead to confusion about their meanings. In this post, I will discuss how and why they are different.
In Node.js, each file is treated as a module and we need to explicitly export what we want to use outside of that module (file).
The exported piece of code which can be an object, function or even a class may then be required in other modules of the application.
Before the code we require is executed, Node.js wraps all of it in a function:
(function(exports, require, module, __filename, __dirname) {
// module code
})
This is why the variables we define with const
and let
in the module will stay private
(they will remain inside the wrapper function's scope) and the arguments of the wrapper function (including __dirname
and __filename
) will be local variables belonging to that module.
__dirname is a string and displays the directory name of the current folder. It can be used and logged as is:
console.log(__dirname); // DIRECTORY_NAME_WITH_PATH
__dirname seems to be part of the global object but - as we have seen - it's local
and is specific to the given module!
__filename is also a string and is the name of the current module (which is a file):
console.log(__filename); // FILE_NAME_WITH_PATH
Similarly to dirname, filename can be used as is and it exists in the module.
process.cwd() returns the current working directory of the Node.js process that is running - hence the name of the method:
console.log(process.cwd()); // DIRECTORY_NAME_OF_THE_PROCESS_WITH_PATH
This method is the odd -one- out as process.cwd() lives in the process module and not in the exported module itself. The process
object is a global
and as such, it can be used without require
-ing it.
It's easy to confuse __dirname
and process.cwd()
. The key difference is that __dirname
is specific to the given module
(file), while process.cwd()
is a method of the global
process object returning the directory name of the file from where the process was run.
filename is the little brother of dirname with a difference of showing the name of the file instead of the folder name.