规范化NodeJS中的路径(Normalizing the Paths in NodeJS)

系统教程 行业动态 更新时间:2024-06-14 16:57:40
规范化NodeJS中的路径(Normalizing the Paths in NodeJS)

我正在尝试规范化NodeJS的路径,因此无论用户输入(*nix/windows) ,路径都应该可以通过node path访问。

Ex: c:/test/test.xml c:\\test\test.xml c:\test/test.xml /usr/var/test.xml /usr/var\test.xml

这些应该被规范化,以便path lib可以访问它们。 我尝试在输入path.normalize上使用path.normalize ,它不起作用。 输出路径字符串与输入相同,而不是/usr/var/test.xml

I am trying to normalize the paths in NodeJS, so that irrespective of user input (*nix/windows), the path should be accessible by node path.

Ex: c:/test/test.xml c:\\test\test.xml c:\test/test.xml /usr/var/test.xml /usr/var\test.xml

These should be normalized so that path lib can access them. I tried using path.normalize on the input /usr/var\test.xml, it didn't work. the output path string is same as input instead of /usr/var/test.xml

最满意答案

我写了自己的简单功能来实现这一点

export function pathToNix(pathStr: string) { var p = path.normalize(pathStr); var path_regex = /\/\//; p = p.replace(/\\/g, "/"); while (p.match(path_regex)) { p = p.replace(path_regex, "/"); } return p; }

澄清一些事情--Windows支持* nix类型文件结构(c:/test/a.txt)。 因此将所有路径转换为* nix格式。

I have written myself simple function to achieve this

export function pathToNix(pathStr: string) { var p = path.normalize(pathStr); var path_regex = /\/\//; p = p.replace(/\\/g, "/"); while (p.match(path_regex)) { p = p.replace(path_regex, "/"); } return p; }

To clarify few things - Windows supports *nix type file structure (c:/test/a.txt). Thus converted all paths to *nix format.

更多推荐

本文发布于:2023-04-13 12:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/1c343b481072f1b8d1a53a570fb6cccd.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   NodeJS   Paths   Normalizing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!