如何确定 JavaScript 中的操作系统路径分隔符?

发布于 2024-07-05 05:16:20 字数 46 浏览 4 评论 0原文

在 JavaScript 中如何判断运行脚本的操作系统中使用了什么路径分隔符?

How can I tell in JavaScript what path separator is used in the OS where the script is running?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

天邊彩虹 2024-07-12 05:16:20

正确答案

所有操作系统都接受 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 被设置为索引 00 之间的子字符串(indexOf('/')C:\Program Files\Notepad\Notepad++.exe 中的 -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

这就是大家!

The Correct Answer

Yes all OS's accept CD ../ or CD ..\ or CD .. regardless of how you pass in separators. But what about reading a path back. How would you know if its say, a 'windows' path, with ' ' and \ allowed.

The Obvious 'Duh!' Question

What happens when you depend on, for example, the installation directory %PROGRAM_FILES% (x86)\Notepad++. Take the following example.

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);
    }
}

What happened!?

targetDir is being set to a substring between the indices 0, and 0 (indexOf('/') is -1 in C:\Program Files\Notepad\Notepad++.exe), resulting in the empty string.

The Solution...

This includes code from the following post: How do I determine the current operating system with Node.js

myGlobals = { isWin: false, isOsX:false, isNix:false };

Server side detection of OS.

// 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; }

Browser side detection of OS

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;

Helper Function to get the separator

function getPathSeparator(){
    if(myGlobals.isWin){
        return '\\';
    }
    else if(myGlobals.isOsx  || myGlobals.isNix){
        return '/';
    }

    // default to *nix system.
    return '/';
}

// modifying our getDir method from above...

Helper function to get the parent directory (cross platform)

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() must be intelligent enough to know which its looking for.

You can get even really slick and check for both if the user is inputting a path via command line, etc.

// 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);

You can also use 'path' module and path.sep as stated above, if you want to load a module to do this simple of a task. Personally, i think it sufficient to just check the information from the process that is already available to you.

var path = require('path');
var fileSep = path.sep;    // returns '\\' on windows, '/' on *nix

And Thats All Folks!

鸢与 2024-07-12 05:16:20

正如此处已经回答的那样,您可以使用 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

As already answered here, you can find the OS specific path separator with path.sep to manually construct your path. But you can also let path.join do the job, which is my preferred solution when dealing with path constructions:

Example:

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
旧人哭 2024-07-12 05:16:20

在 javascript 中,您可以从 window.navigator.userAgent 获取此信息

In javascript you can get this information from window.navigator.userAgent

不醒的梦 2024-07-12 05:16:20

当然,即使在 Windows 上,您始终可以使用 / 作为路径分隔符。

引用自http://bytes.com/forum/thread23123.html

所以,情况可以总结一下
相当简单:

  • 自 DOS 2.0 以来的所有 DOS 服务和所有 Windows API 均接受转发
    斜杠或反斜杠。 一直都有。

  • 标准命令 shell(CMD 或 COMMAND)都不会接受转发
    斜杠。 甚至“cd ./tmp”示例
    上一篇文章中给出的失败。

Afair you can always use / as a path separator, even on Windows.

Quote from http://bytes.com/forum/thread23123.html:

So, the situation can be summed up
rather simply:

  • All DOS services since DOS 2.0 and all Windows APIs accept either forward
    slash or backslash. Always have.

  • None of the standard command shells (CMD or COMMAND) will accept forward
    slashes. Even the "cd ./tmp" example
    given in a previous post fails.

忘羡 2024-07-12 05:16:20

node.js 中使用 path 模块 返回特定于平台的文件分隔符。
编辑示例

path.sep  // on *nix evaluates to a string equal to "/"

:根据下面 Sebas 的评论,要使用它,您需要将其添加到 js 文件的顶部:

const path = require('path')

Use path module in node.js returns the platform-specific file separator.
example

path.sep  // on *nix evaluates to a string equal to "/"

Edit: As per Sebas's comment below, to use this, you need to add this at the top of your js file:

const path = require('path')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文