如何确定 JavaScript 中的操作系统路径分隔符?
在 JavaScript 中如何判断运行脚本的操作系统中使用了什么路径分隔符?
How can I tell in JavaScript what path separator is used in the OS where the script is running?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正确答案
是所有操作系统都接受 CD ../ 或 CD ..\ 或 CD .. 无论您如何传递分隔符。 但是读取返回路径又如何呢? 你怎么知道它是否是一个“windows”路径,允许使用
' '
和\
。明显的“呃!” 问题
例如,当您依赖安装目录
%PROGRAM_FILES% (x86)\Notepad++
时会发生什么情况。 以下面的例子为例。发生了什么!?
targetDir
被设置为索引0
和0
之间的子字符串(indexOf('/')
是C:\Program Files\Notepad\Notepad++.exe
中的-1
),导致空字符串。解决方案...
这包括以下帖子中的代码:如何使用 Node.js 确定当前操作系统
服务器端检测操作系统。
浏览器端检测操作系统
帮助函数以获取分隔符
帮助函数获取父目录(跨平台)
getDir()
必须足够智能才能知道它在寻找哪个目录。如果用户通过命令行输入路径等,您甚至可以变得非常灵活并检查两者。
如果您想加载模块来执行此简单操作,您还可以使用如上所述的“path”模块和path.sep的一个任务。 就我个人而言,我认为仅检查您已经可用的流程中的信息就足够了。
这就是大家!
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.What happened!?
targetDir
is being set to a substring between the indices0
, and0
(indexOf('/')
is-1
inC:\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
Server side detection of OS.
Browser side detection of OS
Helper Function to get the separator
Helper function to get the parent directory (cross platform)
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.
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.
And Thats All Folks!
正如此处已经回答的那样,您可以使用
path.sep
找到操作系统特定的路径分隔符来手动构建路径。 但您也可以让path.join
完成这项工作,这是我在处理路径构造时的首选解决方案:示例:
As already answered here, you can find the OS specific path separator with
path.sep
to manually construct your path. But you can also letpath.join
do the job, which is my preferred solution when dealing with path constructions:Example:
在 javascript 中,您可以从
window.navigator.userAgent
获取此信息In javascript you can get this information from
window.navigator.userAgent
当然,即使在 Windows 上,您始终可以使用 / 作为路径分隔符。
引用自http://bytes.com/forum/thread23123.html:
Afair you can always use / as a path separator, even on Windows.
Quote from http://bytes.com/forum/thread23123.html:
在
node.js 中使用
返回特定于平台的文件分隔符。path
模块编辑示例
:根据下面 Sebas 的评论,要使用它,您需要将其添加到 js 文件的顶部:
Use
path
module innode.js
returns the platform-specific file separator.example
Edit: As per Sebas's comment below, to use this, you need to add this at the top of your js file: