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/

相关文章:

node.js - 将证书凭据与 msal-node 结合使用

javascript - 尝试通过 NodeMailer Mailgun 传输发送 PDF 时出现 400 错误

php - PHP 中的脚本路径有未解析的符号链接(symbolic link)吗?

algorithm - 访问所有节点的最短路径

c++ - 我的操作系统中的 mykernel.iso 执行错误

operating-system - 如何测试引导加载程序

javascript - UserModel 不可分配给文档类型的参数 | nulll [带 typescript 的 Mongoose ]

node.js - Sequelize 如何转换对象列表

objective-c - 解析 NSString 中的真实路径,不带 ".."(之前的目录引用)

python - 监控同步: Implementing multiple condition variables