Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly create cross platform paths with Nodejs?

I have a project and I build path from token strings using path join e.g.

 let myPath = path.join('root', 'path01')

Normally I develop on a POSIX dev machine so no issues at all... but (Unexpected) is that if I run the app on windows it will build paths backslashed

And finally the app is deployed on a POSIX system so it will produce possibly wrong expectations (if starting to develop from windows)...

What's the best way to treat paths with nodejs/javascript so to have them working on all platforms?

like image 673
koalaok Avatar asked Oct 27 '25 06:10

koalaok


2 Answers

Use Upath (Universal Path), a drop-in replacement to Node's path library:

  • https://www.npmjs.com/package/upath

I've just discovered it, and it's brilliant.

like image 116
Dave Stewart Avatar answered Oct 28 '25 19:10

Dave Stewart


What's the best way to treat paths with nodejs/javascript so to have them working on all platforms?

You are already using the best way, which is by using the path module functionality.

Normally I develop on a POSIX dev machine so no issues at all... but (Unexpected) is that if I run the app on windows it will build paths backslashed

This should be expected, because that's the whole purpose of the using path.join. When your code runs, path.join will join your path using the correct delimiter for the operating system, i.e. / on POSIX and \ on Windows.

And finally the app is deployed on a POSIX system so it will produce possibly wrong expectations (if starting to develop from windows)...

There won't be an issue, since you are running on POSIX, path.join will create a path suitable for your POSIX system.

like image 43
leitning Avatar answered Oct 28 '25 19:10

leitning



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!