Last updated: Apr 5, 2024
Reading timeยท2 min

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.
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);

If you use the ES6 modules import/export syntax, use the following syntax instead.
// ๐๏ธ 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.

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.
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.
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 can also pass multiple arguments to the resolve() method.
const {resolve} = require('path'); // ๐๏ธ if using ES6 Modules syntax // import { resolve } from 'path'; // ๐๏ธ /foo/bar/baz console.log(resolve('/foo/bar', './baz')); // ๐๏ธ /baz console.log(resolve('/foo/bar', '/baz'));
You might also see the __dirname and __filename variables being used.
// ๐๏ธ "/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.
You can learn more about the related topics by checking out the following tutorials: