How to determine if a given path is absolute / relative and convert it to absolute for file manipulation?

I am writing small windows script in javascript / jscript to find a match for the regular expression with the string I received by manipulating the file.

The path to the file can be provided relative or absolute. How to determine if a given path is absolute / relative and convert it to absolute for file manipulation?

+4
source share
2 answers

How to determine if a given path is absolute / relative ...

From the MSDN article Naming Files, Paths, and Namespaces :

The file name refers to the current directory if it does not start with one of the following:

  • A UNC name of any format that always starts with two backslash characters ("\\"). See the next section for more information.
  • The backslash drive designation, for example, "C: \" or "d: \".
  • The only backslash, for example, "\ directory" or "\ file.txt". This is also called the absolute path.

So, strictly speaking, an absolute path is one that starts with one backslash ( \ ). You can check this condition as follows:

 if (/^\\(?!\\)/.test(path)) { // path is absolute } else { // path isn't absolute } 

But often on the absolute path we mean a fully qualified path. In this case, you need to check all three conditions in order to distinguish between full and relative paths. For example, your code might look like this:

 function pathIsAbsolute(path) { if ( /^[A-Za-z]:\\/.test(path) ) return true; if ( path.indexOf("\\") == 0 ) return true; return false; } 

or (using one regex and slightly less readable):

 function pathIsAbsolute(path) { return /^(?:[A-Za-z]:)?\\/.test(path); } 

... and convert it to an absolute value for file manipulation?

Use the FileSystemObject.GetAbsolutePathName method:

 var fso = new ActiveXObject("Scripting.FileSystemObject"); var full_path = fso.GetAbsolutePathName(path); 
+5
source

To check if the path is relative or absolute, find the leading / . If it does not have one, you need to combine the path to the base path. Some programming environments have a "current working directory", but there is no Javascript that lives in the browser, so you just need to choose the base path and stick to it.

 function full_path(my_path) { var base_path = "/home/Sriram/htdocs/media"; var path_regex = /^\/.*$/; if(path_regex.test(my_path)) { return my_path; } else { return base_path + my_path; } } 

Paths may contain newline characters that do not match javascript regex . so you might want to develop a more complex regex to make sure that all paths work correctly. However, I would think that this is beyond the scope of this answer and my knowledge. :-)

+1
source

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


All Articles