Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i robustly detect a relative path in node.js

Maybe i am making it to hard (and i should just look for a prefix of ./ and ../) but I don't want to re-invent the wheel and write a function to correctly detect relative paths (for all platforms, etc.)

Existing library?

Are there npm packages that do this? Surely this problem has been solved...

Approaches?

Barring an existing library, my intended approach was to use the path module functions to join the possibly relative path to a known prefix, and then see what the result was, with the assumption that path.join('some_base', possiblyRelative) would allow some sort of distinguishing characteristic in a platform safe way.

Any other suggestions? Approaches?

like image 599
el2iot2 Avatar asked Mar 13 '13 01:03

el2iot2


2 Answers

UPDATE2: TomDotTom found a more robust answer here: How to check if a path is absolute or relative

Reproduced here (but in the inverse):

var path = require('path');
function isRelative(p) {
  return path.normalize(p + '/') !== path.normalize(path.resolve(p) + '/');
}

For node v0.12 and above, I recommend path.isAbsolute instead.

like image 125
B T Avatar answered Oct 08 '22 04:10

B T


It's a little late but for others searching on the same issue:

since node version 0.12.0 you have the the path.isAbsolute(path) function from the path module. To detect if your path is relative use the negation of it:

i.e:

var path = require('path');
if( ! path.isAbsolute(myPath)) {
    //...
}
like image 42
chresse Avatar answered Oct 08 '22 03:10

chresse