Node.js Globals
__dirname: This global variable provides the current directory path of the script being executed
76
In Node.js, __dirname
is a special global variable that provides the absolute path of the directory containing the currently executing script. It returns the complete path of the directory in which the script is located.
The __dirname
variable is very useful in cases where a file needs to be read or written to the current directory, or when a file path is required to be specified relative to the current directory. It can be used to construct file paths relative to the current directory and is often used with the fs
module to manipulate files.
For example, if the current directory for the execution of the script is /home/user/projects/nodeapp
, then __dirname
would return /home/user/projects/nodeapp
.
const fs = require('fs') const path = require('path') //reading a file from the current directory fs.readFile(path.join(__dirname, 'testfile.txt'), (err, data) => { if (err) console.log(err); console.log(data.toString()); })
In this code snippet, path.join()
is used to construct a path to the testfile.txt
located in the current directory, and the fs.readFile()
method is used to read the contents of the file.
Therefore, __dirname
is a handy global variable in Node.js that returns the absolute path of the directory containing the currently executing script, making it easier to load and manipulate files within that directory or its subdirectories.
March 27, 2023