我在 Windows 上开发,但需要知道如何将 Windows 路径(带有反斜杠 \
)转换为带有正斜杠 (/
) 的 POSIX 路径?
我的目标是将 C:\repos\vue-t\tests\views\index\home.vue
转换为 C:/repos/vue-t/tests/views/索引/home.vue
所以我可以在我正在写入磁盘的文件的导入中使用它
const appImport = `
import Vue from "vue"
import App from '${path}'
function createApp (data) {
const app = new Vue({
data,
render: h => h(App)
})
return app
}`
//this string is then written to the disk as a file
我不希望.replace(/\\/g, '/')
字符串,而宁愿使用require('path')
函数。
最佳答案
鉴于所有其他答案都依赖于安装(太大或太小)第三方模块:这也可以作为相对路径的单线来完成(你应该使用 99.999% 的时间已经)使用 Node 的标准库 path
模块,更具体地说,利用其专用的 path.posix
和 path.win32
命名空间属性/函数(在 Node v0.11 中引入):
const path = require("path");
// ...
const definitelyPosix = somePathString.split(path.sep).join(path.posix.sep);
这会将您的路径转换为 POSIX 格式,无论您是否已经在 POSIX 兼容平台或 Windows 上,都不需要任何类型的外部依赖。
关于javascript - 如何使用 Node 路径将 Windows 路径转换为 posix 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53799385/