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

Updated: September 1, 2022 By: Snowball Post a comment

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles