正确答案
是所有操作系统都接受 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 之间的子字符串(indexOf('/') 在C:\Program Files\Notepad\Notepad++.exe 中是-1),导致空字符串。
解决方案...
这包括来自以下帖子的代码:How do I determine the current operating system with 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
这就是所有人!