Do you need to use path.join in Node.js?

as everyone knows that windows makes backslashes, where unix does forward slashes. Node.js provides path.join() to always use the correct forward slash. So, for example, instead of writing unix only 'a/b/c' instead you would do path.join('a','b','c') .

However, it seems that despite this difference, if you do not normalize your paths (for example, using path.join) and just write paths like a/b/c Node.js does not have problems running your scripts on Windows ...

So, is there any advantage over writing path.join('a','b','c') over 'a/b/c' ? since both of them work regardless of the platform ...

+103
path
Mar 18 2018-12-18T00:
source share
4 answers

Windows file systems have no problem using either redirects or backslashes as path separators (this was the case in DOS days). The only real problem is that Windows command line processors (or, more specifically, Windows command line utilities) tend to interpret slashes as qualifiers for options, not path components. Therefore, you need a return path if you need to pass the path to the Windows command line as a subprocess. In addition, Windows API calls (and higher-level language methods that invoke the Windows API) that return paths will use a backslash, so even if you don't pass them to subprocesses, you need to normalize them.

+84
Mar 21 '12 at 6:15
source share

path.join will take care of unnecessary delimiters that may occur if the specified patterns come from unknown sources (for example, user input, third-party APIs, etc.).

So path.join('a/','b') path.join('a/','/b') , path.join('a','b') and path.join('a','/b') will give a/b .

Without use, you would usually make expectations about the start and end of the joints, knowing that they don't have a single slash.

+69
Feb 27 '14 at 20:59
source share

I use paths.join to ensure that the folder delimiters are in the right places, and not necessarily to use crosses or backslashes. For example:

 path.join("/var/www", "test") 

Correctly insert the separator between www and test /var/www/test

+40
Mar 18 2018-12-18T00:
source share

Short answer:

All fs.* Functions (e.g. fs.open , etc.) handle the path name for you. Thus, you do not need to use path.join yourself and make the code invisible.

Long answer:

All fs.* path._makeLong(path) call path._makeLong(path) , which in turn calls path.resolve(path) , which has a special RegExps for Windows that takes backslash \ or slashes / into account. You can verify this for yourself by looking at the source code:

+26
Nov 30 '12 at 17:49
source share



All Articles