简体   繁体   中英

What is the practical purpose of path.join?

I am using this passed down code

const DIST_DIR = path.join(__dirname, '/client-react/dist');

and I looked at the official docs however the docs did not show a practical example.

From a conceptual point of view path.join appears to make paths consistent across platforms but I don't know what this means practically.

Can someone provide a practical example?

Different OSes use different path separators. For instance, Windows uses a backslash \\ to separate directories while Unix based systems (eg Linux, macOS) use a forward slash / to do the same.

Using path.join , you make sure that your path is concatenated with the right separator for the OS it is running on.

In contrast, if you had used normal string concatenation functions or operators your path separators would have been hard coded, so to speak and your script/program would've worked on one system but failed on another.

In platform agnostic programming languages, like JS, it is important to outsource platform specific functions to such libraries to make sure that our script is robust enough to endure different OSes.

If you're running your node script on Windows, the folder separator is '\\'. File/directory paths look like this 'C:\\home\\user\\Documents\\a.doc'

On Linux and Mac, it is '/'. Full file/directory paths look like this '/home/user/Documents/a.doc'

If you were trying to manually build up a file path in your node script, and you wanted the script to function correctly on both windows and linux/mac, you would need to use an if condition to check which path-separator to use. path.join takes care of that for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM