我正在不同的操作系统上运行测试,我期望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 / OStringUtils.toNativePath("../foo.txt")
StringUtils.toNativePath("..\\foo.txt")
关于node.js - 基于操作系统确认路径字符串类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800131/