Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a path is absolute or relative

UNIX absolute path starts with '/', whereas Windows starts with alphabet 'C:' or '\'. Does node.js has a standard multiplatform function to check if a path is absolute or relative ?

like image 463
Manuel Di Iorio Avatar asked Feb 11 '14 10:02

Manuel Di Iorio


People also ask

How do you know if a path is absolute or relative?

This just checks if the path string has either "/./" or "/../". and returns true on any and false on neither. If any of the two tests is true then the path string is relative.

How do you know if a path is absolute or relative in Python?

path. isabs() method in Python is used to check whether the specified path is an absolute path or not. On Unix platforms, an absolute path begins with a forward slash ('/') and on Windows it begins with a backward slash ('\') after removing any potential drive letter.


2 Answers

Since node version 0.12.0 you can use the path.isAbsolute(path) function from the path module.

i.e:

var path = require('path'); if(path.isAbsolute(myPath)) {     //... } 
like image 74
chresse Avatar answered Sep 21 '22 13:09

chresse


You could use

path.resolve(yourPath)===yourPath 

If your path isn't normalized, use

path.resolve( yourPath ) == path.normalize( yourPath ) 
like image 32
Denys Séguret Avatar answered Sep 18 '22 13:09

Denys Séguret