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:

1
const processDir = process.cwd()

File/Module Directory

And we can get the directory in which the currently executing file is in with:

1
const fileDir = __dirname

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

1
const { join } = require('path')
2
3
const path1 = join(basePath, './downdir/myfile.txt')
4
const path2 = join(basePath, '../updir')

Absolute Path from Process Directory

To get an absolute path from the process directory, you can use the path module’s resolve function:

1
const { resolve } = require('path')
2
3
const absPath = resolve('./downdir/myfile.txt')

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()

1
const absPath = join(process.cwd(), './downdir/myfile.txt')

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:

1
const { join } = require('path')
2
3
const absPath = join(__dirname, './downdir/myfile.txt')