【问题标题】:Way to affirm path string type based on operating system基于操作系统的路径字符串类型确认方法
【发布时间】:2015-08-04 03:24:12
【问题描述】:

我正在不同的操作系统上运行测试,我希望路径格式能够与 posix 一起返回。

这是我遇到的错误类型:

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

如何确认posixAffirm("../foo.txt") 之类的路径并让它根据 windows 或 posix 呈现出动态正确的路径格式字符串。

【问题讨论】:

  • “确认”是什么意思?您能否编辑您的问题以包含输入和所需输出的一些示例?

标签: node.js path operating-system


【解决方案1】:

这是我使用的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")

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2012-10-13
    相关资源
    最近更新 更多