Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change path separator using path module

Tags:

path

node.js

Here is my code:

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

To get the appropriate image path, I have to split by the path separator and then join the array with the appropriate slash. Does anyone know of a more efficient way of doing this?

like image 352
dopatraman Avatar asked Mar 08 '13 04:03

dopatraman


2 Answers

Also, you can always get forward slashes in paths by specifically using the posix path apis:

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

EDIT: This api is only available in versions of node 0.12 or higher.

like image 69
justin.m.chase Avatar answered Oct 23 '22 22:10

justin.m.chase


John's answer will only replace the first instance of a '\'

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

Would replace all of them.

You can pass the 'g' flag to .replace but this non-standard.

like image 31
ErisDS Avatar answered Oct 23 '22 23:10

ErisDS