How to Convert Relative to Absolute path in Nodejs | Javascript

In this short tutorial, You will learn how to convert relative path to absolute path in Nodejs Application with an example. You can also check other posts on npm command deprecate option is deprecated

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 a path module, that works with file paths.

relative paths are converted to absolute paths using the 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 an absolute path i.e /input/test.pdf

an example using dirname and filename dirname returns the root directory 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?

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

Please note that this method only checks paths in the file system paths, not related to the URL path. And, It is not reliable when you are using ~ in Unix and Linux, and returns 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 paths in Nodejs.