How can I confidently determine the relative path in node.js

Maybe I'm doing it hard (and I should just look for the prefix ./ and ../ ), but I don't want to reinvent the wheel and write a function to correctly determine relative paths (for all platforms, etc.)

existing library?

Are there npm packages that do this? Of course, this problem has been resolved ...

Approaches?

The ban on the existing library was to use the functions of the path module to join possible relative path to a known prefix, and then see what the result was, provided that path.join('some_base', possiblyRelative) allows a kind of distinguishing characteristic in safe the platform.

Any other suggestions? Approaches?

+4
source share
3 answers

A bit late, but for others who are looking for the same issue:

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

i.e:

 var path = require('path'); if( ! path.isAbsolute(myPath)) { //... } 
+7
source

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

Reproduced here (but in reverse):

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

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

+10
source
 function isRelative(str) { //Remove quotes as it can potentially mess up the string str=str.replace("\'\"",''); return str.substring(0,2)=="./"||str.substring(0,3)=="../"; } 

In this example, we allow relative lines to start the line path.

0
source

Source: https://habr.com/ru/post/1468868/


All Articles