{

How to Convert Relative to Absolute path in Nodejs | Javascript


How to Convert Relative to Absolute path in Nodejs Example

In this short tutorial, You will learn how to convert relative path to absolute path in Nodejs Application with example.

absolute path and relative path in Nodejs

A resource path that starts at the application root is known as an absolute path. i.e. always begins with the /.

Relative path is a relative path to the resource, which does not begin with /.

Let’s say, you have a NodeJS application with the following directory or folder structure.

empapp
  -src
   --models
    ---employee.js
   --controller
    ---EmpController.js
  -input
   --test.doc
index.html
package.json

if you are using the test.doc file in EmpController.js, how do you refer to this file (test.doc). Then Absolute path is /input/test.doc.

/ treats as root or application

and a relative path is ../input/test.doc .. refers to the parent folder

Convert relative path to absolute path in Nodejs

Nodejs provides path module, working with file paths.

relative paths are converted to absolute paths using below two approaches

path.resolve Given input path of test.doc is ../input/test.doc, We will see how to convert this to an absolute path.

const path = require("path"); 
path.resolve('../input/test.doc'); // give /input/test.pdf

The output is absolute path i.e /input/test.pdf

an example using dirname and filename dirname returns root director where the current file exists. Filename gives the name of the file

var path = require('path');
console.log('one - ', __dirname);// prints absolute path of an application
var here = path.basename(__dirname__) + '/input/test.pdf' ;

How to Check given path is absolute or relative in Nodejs?

relative path should not starts /. path.isAbsolute() method checks and return true - for absolute paths,else return false.

Please note that this method only checks path in the file system paths, not related to URL path. And, It is not reliable when you are using ~ in Unix and Linux, and return false data.

var path = require("path");
console.log(__dirname); //b:/nodejsapp
console.log(path.isAbsolute(__dirname)); //true
console.log(path.isAbsolute("../")); //false

And Another reliable way is to use resolve and normalize and compare values

path.resolve(__dirname) === path.normalize(__dirname) 

Conclusion

To Sum up, Learned Absolute and relative path in Nodejs

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.