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
Absolute path is path of the resource starts from application root, always starts with /. Relative path is path of of the resource relative path of an resource, it will not starts with /.
For example, Let’s have a NodeJS application has directory or folder structure as follows
empapp -src --models ---employee.js --controller ---EmpController.js -input --test.doc index.html package.json
if you are using test.doc file in EmpController.js, how do you refer this test.doc. Then Absolute path is /input/test.doc.
/ treats as root or application
and relative path is ../input/test.doc .. refers to parent folder
Convert relative path to absolute path in Nodejs
path module, working with file paths.
relative paths are converted to absolute paths using below two approaches
- __dirname and - __filename
path.resolve Given input path of test.doc is ../input/test.doc, We will see how to convert this to 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 current file exists. Filename gives 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' ;
Check given path is absolute or relative
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, 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)