I know of this question: Convert relative path to absolute using JavaScript
But it is about JavaScript that runs in a browser. My JS runs on Windows (WSH).
That means I don't have the following objects: window
, document
and console
.
I already figured a few things out:
Since you can use slash (/) instead of a backslash () in a path and you don't need to escape a slash, I'll try to work with / ... I also figured it would be best to remove the trailing slash if there is one.
So here are a couple of things I already figured out:
var currentDir = new ActiveXObject("WScript.Shell").CurrentDirectory.replace(/\\/g, '/'); //current directory with slashes
var root = currentDir.substring(0,2) //e.g. C: or D: (without trailing slash)
There are a couple of of different relative pathes that have to be converted correctly. Just to make sure, here are some examples:
If the script was launched from C:\folder1\folder2\folder3
the paths should be converted accordingly:
/
=> C:
/test
=> C:/test
\test
=> C:/test
\test\
=> C:/test
..
=> C:/folder1/folder2
C:\folder1\folder2\folder3\..\folder3-1\test.js
=> C:/folder1/folder2/folder3-1/test.js
../../test.js
=> C:/folder1/test.js
D:\
=> D:
.
=> C:/folder1/folder2/folder3
./test
=> C:/folder1/folder2/folder3/test
.\..\..
=> C:/folder1
D:/folder/another folder/file.js/../../other file.js
=> D:/folder/other file.js
And yeah.. I'm kind of stuck here. I guess this requires some kind of parsing loop, but I just couldn't come up with the solution.
I hope you can help me out here. :/