Borislav Hadzhiev
Sun Mar 27 2022·1 min read
Photo by Bruce Mars
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);
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 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
.