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.)
Are there npm
packages that do this? Surely this problem has been solved...
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?
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.
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)) {
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With