node.js - 基于操作系统确认路径字符串类型的方法

标签 node.js path operating-system

我正在不同的操作系统上运行测试,我期望posix会返回一种路径格式。

这是我遇到的错误:

Uncaught AssertionError: expected "..\\foo.txt" to equal "../foo.txt"


如何确认类似posixAffirm("../foo.txt")的路径,并使其基于Windows或posix呈现出动态正确的路径格式字符串。

最佳答案

这是我使用的TypeScript代码片段:



class StringUtils {
  // SiwachGaurav's version from http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript
  static replaceAll(str: string, find: string, replace: string): string {
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&'),'g'), replace);
  }

  // Returns file path with OS-native slashes
  static toNativePath(str: string): string {
    var os = ExternalInterfaces.require_os();
    if (os.platform() == "win32")
      // Convert Unix to Windows
      return StringUtils.replaceAll(str, "/", "\\");
    else
      // Convert Windows to Unix
      return StringUtils.replaceAll(str, "\\", "/");
  }

  // Returns file path with POSIX-style slashes
  static toPosixPath(str: string): string {
    // Convert Windows to Unix
    return StringUtils.replaceAll(str, "\\", "/");
  }
}



检查两个路径是否指向相同

StringUtils.toPosixPath("..\\foo.txt") == StringUtils.toPosixPath("../foo.txt")
将路径传递到node.js文件I / O

StringUtils.toNativePath("../foo.txt")

StringUtils.toNativePath("..\\foo.txt")

关于node.js - 基于操作系统确认路径字符串类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800131/

相关文章:

c - 为什么 fork() 的输出是特定顺序的?

memory-management - 虚拟内存和物理内存有什么区别?

node.js - Express/Node 依赖项的模式 : Can I use a separate services file for "app" instance?

mysql - 在 nodejs 中编写 SQL 查询

graph - Neo4J Cypher - 寻找两条路径的交汇点

python - 如何在 python 中添加相对路径以查找具有短路径的图像和其他文件?

ios - 2011年Mac的发展

javascript - 无法将 Brain.JS 导入我的 NodeJS 脚本

javascript - 是否可以将流从一个功能转发到另一个功能?

java - 如何在Java项目文件中找到文件的路径?