koalaok
koalaok

Reputation: 5740

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?

Upvotes: 4

Views: 3991

Answers (3)

leitning
leitning

Reputation: 1506

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.

Upvotes: 1

Dave Stewart
Dave Stewart

Reputation: 2534

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

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

Upvotes: 4

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

You've got a few friends that will help, I'd start off by looking at the Node path object and its methods. path.delimiter in specific to start with, but there may be some short-cut methods that can help you as well.

https://nodejs.org/api/path.html#path_path_delimiter

Upvotes: 0

Related Questions