Kinda Code
Home/Node/Node.js: Turn a Relative Path into an Absolute Path

Node.js: Turn a Relative Path into an Absolute Path

Last updated: September 01, 2022

In Node.js, you can convert a relative path to an absolute path simply by using the path module, like this:

import path from 'path'
// if you're using commonJS, use "require" instead of "import":
// const path = require('path')

// a file that locates at the project root
console.log(path.resolve('./test.txt'));

// a file that locates at a subdirectory of the project root
console.log(path.resolve('src/kindacode.jpg'))

// a file that locates at two folders up from the project root
console.log(path.resolve('../../some-thing.txt'));

This is my output on macOS (if you’re using Windows, your result will be more or less different):

/Users/goodman/Desktop/Dev/node/kindacode_js/test.txt
/Users/goodman/Desktop/Dev/node/kindacode_js/src/kindacode.jpg
/Users/goodman/Desktop/Dev/some-thing.txt

That’s it. Further reading:

You can also check out our Node.js category page for the latest tutorials and examples.