Node.js Dirname vs Resolve
25 September 2020
Updated: 03 September 2023
Node.js has a few methods by which we can get the directory in which we are currently executing, and get paths relative to it
Get the Current Directory
Process Directory
We can get the working directory from where we started the node
script with:
File/Module Directory
And we can get the directory in which the currently executing file is in with:
Get Path to a Target Location
To get an absolute path to a specific target file/directory we have a few methods
Joining Paths
We can use the path
module’s join
method to get a path given any path pieces you can go up or down a directory using the ../
notation
Absolute Path from Process Directory
To get an absolute path from the process directory, you can use the path
module’s resolve
function:
Like the
join
method you can also use the../
notation to move up a directory
Using resolve
is basically shorthand for using join
with process.cwd()
Absolute Path from File/Module Directory
If it makes more sense to get the path relative to the executing file, you can use a combination of __dirname
and join
like so: