我正在不同的操作系统上运行测试,我希望 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/