[英]Convert relative path to absolute path on Windows?
我知道这个问题: 使用JavaScript将相对路径转换为绝对路径
但这是关于在浏览器中运行的JavaScript的。 我的JS在Windows(WSH)上运行。
这意味着我没有以下对象: window
, document
和console
。 我已经弄清楚了一些事情:
由于您可以在路径中使用斜杠(/)而不是反斜杠(),并且无需转义斜杠,因此,我将尝试使用/ ...,我也认为最好删除尾部如果有一个,则斜线。
所以这是我已经弄清楚的几件事:
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)
有几个不同的相对路径必须正确转换。 为了确保确定,这里有一些示例:
如果脚本是从C:\\folder1\\folder2\\folder3
则路径应相应地转换:
/
=> 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
是的..我有点卡在这里。 我想这需要某种解析循环,但是我无法提出解决方案。
我希望你能在这里帮助我。 :/
split()
将其转换为数组 <?xml version="1.0"?>
<package>
<job id="default" filename="filepath_operations.wsf">
<script language="jscript">
<![CDATA[
// <beg-block>
// - caption: demo filepath operations in wsh jscript
// rectype: rrmicro004
// dmid: "uu236zogguwfrosk"
// date: "2019-04-12 15:56:17"
// tags: file,path,
// notes: |
// * seealso ;; href="https://stackoverflow.com/questions/33033388/convert-relative-path-to-absolute-path-on-windows"
// <end-block>
// regionbeg_:: vars.init//
var str_currdir;
var lst_pathsteps;
// regionend_://
// regionbeg_:: vars.populate//
str_currdir = new ActiveXObject("WScript.Shell").CurrentDirectory.replace(/\\/g, '/'); //current directory with slashes
lst_pathsteps = str_currdir.split("/");
// regionend_://
// regionbeg_:: pathstep.common.operations//
WScript.Echo("total_pathsteps: " + lst_pathsteps.length); // total_pathsteps
WScript.Echo("root_drive: " + lst_pathsteps[0]); // root_drive
WScript.Echo("full_directory: " + str_currdir); // full_directory
WScript.Echo("this_dir_step: " + lst_pathsteps[lst_pathsteps.length-1]); // this_dir_step
WScript.Echo("parent_dir_step: " + lst_pathsteps[lst_pathsteps.length-2]); // parent_dir_step
WScript.Echo("grandparent_dir_step: " + lst_pathsteps[lst_pathsteps.length-3]); // grandparent_dir_step
WScript.Echo("great1xgrandparent_dir_step: " + lst_pathsteps[lst_pathsteps.length-4]); // great1xgrandparent_dir_step
WScript.Echo("great2xgrandparent_dir_step: " + lst_pathsteps[lst_pathsteps.length-5]); // great2xgrandparent_dir_step
// regionend_://
]]>
</script>
</job>
</package>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.