0

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?

  • Please see this thread - https://stackoverflow.com/questions/9756567/do-you-need-to-use-path-join-in-node-js – Aldrin Dec 17 '18 at 07:00
  • 2
    Possible duplicate of [Do you need to use path.join in node.js?](https://stackoverflow.com/questions/9756567/do-you-need-to-use-path-join-in-node-js) – SanSolo Dec 17 '18 at 07:03

2 Answers2

5

Different OSes use different path separators. For instance, Windows uses a backslash \ to separate directories while Unix based systems (e.g. 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.

kev
  • 1,011
  • 8
  • 15
0

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.

ack_inc
  • 1,015
  • 7
  • 13