2013-03-08 95 views
3

此處更改路徑分隔符是我的代碼:使用路徑模塊

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("/"); 

,獲取相應的圖片路徑,我有路徑分隔符進行分割再加入用適當的斜線排列。有沒有人知道這樣做的更有效的方式?

回答

11

約翰的回答只會取代的「\」

img.src = thisImagePath.replace(new RegExp('\\' + path.sep, 'g'), '/'); 

將取代所有的人的第一個實例。

您可以將'g'標誌傳遞給.replace,但是這個non-standard

7

而且,你總是可以得到正斜槓的路徑,通過專門使用POSIX API的路徑:

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

編輯:這個API是隻在節點0.12或更高版本。

+0

我upvoted這個(回到0)。我猜如果有人在節點0.10或更早的版本上嘗試過它,它可能會降低它的性能,在那裏它不被支持... – laurelnaiad 2016-01-05 17:18:05

+0

謝謝,我編輯它以包含這個警告......但我們現在都使用節點最新的穩定版本對? ;) – 2016-01-05 21:29:50

+1

這是最好的答案。 +1 – 2017-06-01 18:00:00