Get absolute path of file from relative path in Node.js

avatar

Borislav Hadzhiev

Last updated: Mar 27, 2022

banner

Photo from Unsplash

Get absolute path of file from relative path in Node.js #

Use the path.resolve() method to get an absolute path of a file from a relative path in Node.js, e.g. path.resolve('./some-file.js'). The resolve() method will resolve the provided relative path into an absolute path.

index.js
const {resolve} = require('path'); // 👇️ if using ES6 Modules syntax // import { resolve } from 'path'; const absolutePath = resolve('./another-file.js'); // 👇️ "/home/borislav/Desktop/bobbyhadz-js/another-file" console.log(absolutePath);

The path.resolve method takes one or more path segments and resolves them into an absolute path.

get-absolute-path.webp

If you call the resolve() method without passing it an argument, or pass it an empty string, it will return the absolute path of the current working directory.

index.js
const {resolve} = require('path'); // 👇️ if using ES6 Modules syntax // import { resolve } from 'path'; const absolutePath = resolve(''); // 👇️ "/home/borislav/Desktop/bobbyhadz-js" console.log(absolutePath);

You can also go up directories when specifying the relative path.

index.ts
const {resolve} = require('path'); // 👇️ if using ES6 Modules syntax // import { resolve } from 'path'; const absolutePath = resolve('../aws-cli.txt'); // 👇️ "/home/borislav/Desktop/aws-cli.txt" console.log(absolutePath);

You might also see the __dirname and __filename variables being used.

index.ts
// 👇️ "/home/borislav/Desktop/bobbyhadz-js" console.log(__dirname); // 👇️ "/home/borislav/Desktop/bobbyhadz-js/index.js" console.log(__filename);

The __dirname variable returns the directory name of the current module.

For example, if you use the __dirname variable in a module located at /home/user/my-module.js, the __dirname variable would return /home/user.

The __filename variable returns the absolute path of the current module.

So, if you use the __filename variable in a module located at /home/user/my-module.js, the __filename variable would return /home/user/my-module.js.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.