在 JavaScript 中,我如何判断脚本所运行的操作系统使用的路径分隔符是什么?
在 JavaScript 中,我如何判断脚本所运行的操作系统使用的路径分隔符是什么?
node.js
中的 path
模块可以返回特定于平台的文件分隔符。path.sep // on *nix evaluates to a string equal to "/"
编辑:根据Sebas在下面的评论,要使用此功能,您需要在js文件顶部添加以下内容:
const path = require('path')
path.sep
。参考链接:https://nodejs.org/docs/latest/api/path.html#path_path_sep。 - Ionică Bizăuconst path = require('path');
- Sebas在任何情况下,甚至在Windows系统中,您都可以使用“/”作为路径分隔符。
引用自http://bytes.com/forum/thread23123.html:
因此,情况可以简单地总结如下:
从DOS 2.0开始,所有DOS服务和所有Windows API都接受正斜杠或反斜杠。这种方式一直存在。
标准命令行解释器(CMD或COMMAND)都不接受正斜杠。即使在以前的帖子中给出了“cd ./tmp”示例,也会失败。
input type="file"
时,在不同的浏览器上工作不一致,现在通常会报告 C:\fakepath
前缀。因此,反斜杠代替了正斜杠。因此,如果您例如使用 split
获取基本名称进行解析,则无法获得所需内容。 - Volomike是的,所有操作系统都接受CD ../或CD ..\或CD ..无论您如何传递分隔符。但是,如果要读取路径,那该怎么办呢?例如,你如何知道它是一个具有允许' '
和\
的“Windows”路径。
当你依赖于例如安装目录%PROGRAM_FILES% (x86)\Notepad++
时会发生什么。看下面的例子。
var fs = require('fs'); // file system module
var targetDir = 'C:\Program Files (x86)\Notepad++'; // target installer dir
// read all files in the directory
fs.readdir(targetDir, function(err, files) {
if(!err){
for(var i = 0; i < files.length; ++i){
var currFile = files[i];
console.log(currFile);
// ex output: 'C:\Program Files (x86)\Notepad++\notepad++.exe'
// attempt to print the parent directory of currFile
var fileDir = getDir(currFile);
console.log(fileDir);
// output is empty string, ''...what!?
}
}
});
function getDir(filePath){
if(filePath !== '' && filePath != null){
// this will fail on Windows, and work on Others
return filePath.substring(0, filePath.lastIndexOf('/') + 1);
}
}
targetDir
被设置为索引 0
和 0
之间的子字符串(C:\Program Files\Notepad\Notepad++.exe
中indexOf('/')
为-1
),结果为空字符串。
这包括来自以下帖子的代码:如何在Node.js中确定当前操作系统
myGlobals = { isWin: false, isOsX:false, isNix:false };
服务器端操作系统检测。
// this var could likely a global or available to all parts of your app
if(/^win/.test(process.platform)) { myGlobals.isWin=true; }
else if(process.platform === 'darwin'){ myGlobals.isOsX=true; }
else if(process.platform === 'linux') { myGlobals.isNix=true; }
浏览器端的操作系统检测
var appVer = navigator.appVersion;
if (appVer.indexOf("Win")!=-1) myGlobals.isWin = true;
else if (appVer.indexOf("Mac")!=-1) myGlobals.isOsX = true;
else if (appVer.indexOf("X11")!=-1) myGlobals.isNix = true;
else if (appVer.indexOf("Linux")!=-1) myGlobals.isNix = true;
获取分隔符的辅助函数
function getPathSeparator(){
if(myGlobals.isWin){
return '\\';
}
else if(myGlobals.isOsx || myGlobals.isNix){
return '/';
}
// default to *nix system.
return '/';
}
// modifying our getDir method from above...
获取父目录的帮助函数(跨平台)
function getDir(filePath){
if(filePath !== '' && filePath != null){
// this will fail on Windows, and work on Others
return filePath.substring(0, filePath.lastIndexOf(getPathSeparator()) + 1);
}
}
getDir()
必须足够智能以知道它正在查找哪一个。
如果用户通过命令行输入路径等,您甚至可以变得非常聪明,并检查两者。
// in the body of getDir() ...
var sepIndex = filePath.lastIndexOf('/');
if(sepIndex == -1){
sepIndex = filePath.lastIndexOf('\\');
}
// include the trailing separator
return filePath.substring(0, sepIndex+1);
如前所述,如果您想加载一个模块来执行这个简单的任务,您也可以使用“path”模块和path.sep。个人认为,仅检查已经可用的进程信息就足够了。
var path = require('path');
var fileSep = path.sep; // returns '\\' on windows, '/' on *nix
NodeJS
标签 - 你回答了 服务器 和 客户端 的两个方面。你的回答完全 - 实际上 - 回答了这个问题。对于 Node,我认为路径模块很好,因为它不会影响生成的字节码性能,也不应影响可读性(只有一个导入语句)。然而,你是唯一回答客户端的人。这应该被接受。 - Rik如前面所述,您可以使用path.sep
查找特定于操作系统的路径分隔符以手动构建路径。但是,当处理路径构造时,我更喜欢让path.join
来完成这项工作,这是我的首选解决方案:
示例:
const path = require('path');
const directory = 'logs';
const file = 'data.json';
const path1 = `${directory}${path.sep}${file}`;
const path2 = path.join(directory, file);
console.log(path1); // Shows "logs\data.json" on Windows
console.log(path2); // Also shows "logs\data.json" on Windows
window.navigator.userAgent
获取此信息。只需使用“/”,据我所知,它适用于所有操作系统。