9

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?

0

4 Answers 4

22

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I made the same mistake of thinking this would work. As long as each string parameter you pass to relative does not have any path separators, it works. But if you do something like path.posix.relative('./public', 'blah\blah\blah'), the result is ../blah\blah\blah. I took that into account when I made this answer.
Yes true, this will let you build platform specific paths but not repair existing path strings.
14

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.

Comments

3

You can also use the replaceAll string method.

img.src = thisImagePath.replaceAll(path.sep, "/");

Comments

0

I came across this question because I was trying to fix system paths. While the accepted answer works for converting strings to URLs (since they're always '/'), it does not work for file system paths. Below is a more comprehensive answer which I think fits the implied question better.

const ESCAPE = '\\';
const WRONG_SEPARATOR_FILE_SYSTEM = path.sep === path.win32.sep ?
   path.posix.sep :
   path.win32.sep;

const RGX_WRONG_SEPARATOR_FILE_SYSTEM = new RegExp(ESCAPE + WRONG_SEPARATOR_FILE_SYSTEM, 'g');
const RGX_WRONG_SEPARATOR_URL = new RegExp(ESCAPE + path.win32.sep, 'g');

function strToPath(str) {
    return str.replace(RGX_WRONG_SEPARATOR_FILE_SYSTEM, path.sep);
}

function strToUrl(str) {
    return str.replace(RGX_WRONG_SEPARATOR_URL, '/')
}

// using urls
img.src = strToUrl(thisImagePath)

// using files
strToPath('/some/posix/path') // will be correct regardless of system
strToPath('\some\win\path') // will be correct regardless of system

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.