I'm trying to resolve a string to a theoretical, virtual path (created all in the client side), using plain old JavaScript, no NodeJS, nothing (and I tried making a new URL or setting the path to a href etc., but I want this to work inside of a web-worker).
Basically, there is a virtual file system, that starts with, say, "C:/", and goes down like every other path system. Let's say I am given a string as an input such as
"C:/someDir/someOtherDir/someThirdDir/../../folderInSomeDir/fileInFolderInSomeDir.txt"
so this would theoretically be accessing, well, as the name of the file itself says, a file inside of a folder, which itself is inside of the folder named someDir.
The hard part to process is the ../../ part, so the expected output string from the above would be
"C:/someDir/folderInSomeDir/fileInFolderInSomeDir.txt"
I'm just drawing a mental blank as to how exactly to process the ../../ part, I tried splitting up the string by / and looping through the sections, determining if the current string is equal to .., and also keeping track of the current directory which immediately would precede each .., but I'm at a mental blank as to what to do next to get the output string. Here's my function, currently
b.onclick = () => {
out.innerHTML = resolve(p.value)
};
function resolve(path, basePath = "/") {
var pathd = pathify(path)
if(basePath != "/") basePath = resolve(basePath)
var based = pathify(basePath)
var baseDirs = based.split("/")
var directs = pathd.split("/")
var upDirs = 0
var currentDir = ""
var numberDirs
var result
directs.forEach((x, i, ar) => {
if(x == ".." || i == 0 && x == "") {
upDirs++
}
else {
currentDir = x
}
})
result = directs.join("/") //what else do I Do?!
return result
}
function pathify(path) {
var newPath = ""
if(typeof path == "string") {
var slashesDoubled = 0,
dotsDoubed
path.split("").forEach(x => {
var isIts = [
"\n"
]
if(x == "/") {
++slashesDoubled
if(slashesDoubled < 2) newPath += x
isIts.push("/")
} else {
slashesDoubled = 0
}
if(x == ".") {
++dotsDoubed
if(dotsDoubed < 3) newPath += x;
isIts.push(".")
} else if(
1//
) {
dotsDoubed = 0
!isIts.includes(x) && (newPath += x)
}
})
var notAtEnd = "/.".split("")
if(
notAtEnd.includes(newPath[newPath.length - 1])
) {
for(var i = newPath.length - 1; i >= 0; i--) {
if(notAtEnd.includes(newPath[i]))
newPath = newPath.substring(0, newPath.length - 1)
else break;
}
}
}
return newPath
}
<input id=p><button id=b>Resolve the path!</button><br>
<div id=out></div>