使用路径模块更改路径分隔符

时间:2013-03-08 04:35:48

标签: node.js path

这是我的代码:

var thisImageName = thisRow["imagename"];
var thisImagePath = path.relative("./public", __dirname + "/public/uploads/" + thisImageName + ".jpg");
console.log(thisImagePath); // returns __dirname\public\uploads\
img.src = thisImagePath.split(path.sep).join("/");

要获得适当的图像路径,我必须通过路径分隔符进行拆分,然后使用适当的斜杠连接数组。有没有人知道更有效的方法呢?

2 个答案:

答案 0 :(得分:13)

John的回答只会替换'\'

的第一个实例
img.src = thisImagePath.replace(new RegExp('\\' + path.sep, 'g'), '/');

将替换所有这些。

您可以将“g”标记传递给.replace但是non-standard

答案 1 :(得分:11)

此外,您可以通过专门使用posix路径apis来获取路径中的斜杠:

var p = path.posix.relative("./public", imagePath);

编辑:此API仅适用于0.12或更高版本的节点。

相关问题