Example analysis of advantages of path. join of in Node. js

  • 2021-11-13 00:52:51
  • OfStack

You may wonder why you want to use the path. join () method instead of string splicing.


'/path' + '/' + 'to' + '/' + 'test.txt' // '/path/to/test.txt'
 
['/path', 'to', 'test.txt'].join('/') // '/path/to/test.txt'

1. Support for Windows. Windows uses a backslash (\) instead of a forward slash (/) as the path separator.

path. join () will handle this problem for us. Because path. join ('data', 'test. txt') returns' data/test. txt 'on Linux, OSX and Windows.

2. Used to deal with edge situations. When using the file system path, many edge situations will pop up.

For example, if you try to connect two paths manually, you may accidentally get duplicate path separators. The path. join () method handles the opening and ending slashes for us.


path.join('data', 'test.txt') // 'data/test.txt'
path.join('data', '/test.txt') // 'data/test.txt'
path.join('data/', 'test.txt') // 'data/test.txt'
path.join('data/', '/test.txt') // 'data/test.txt'

Extension of knowledge points:

1. path. join () method

The path. join () method combines multiple parameter strings into one path string

console. log (path. join (__dirname, 'a', 'b')); If the path of the current file is E:/node/1, then the splicing is E:/node/1/a/b.

console. log (path. join (__dirname, '/a', '/b', '...')); The/at the beginning of the path does not affect the splicing, … stands for the upper level 1 file, and the result of splicing is: E:/node/1/a

console. log (path. join (__dirname, 'a', {}, 'b')); And path. join () will also help us to check the path string. When the string is illegal, an error will be thrown: Path must be a string.

2. path. resolve () method

path. resolve () method is based on the program as the root directory, as a starting point, parsing out an absolute path according to the parameters

Take the application as the root directory

Ordinary strings represent subdirectories

/represents the absolute path root directory

console. log (path. resolve ()); Get the directory of the application startup file (get the absolute path of the current execution file) E:\ zf\ webpack\ 1\ src

console. log (path. resolve ('a', '/c')); E:/c, because the/slash represents the root directory, so you get E:/c

Therefore, we need to use/slash carefully when splicing

console. log (path. resolve (__dirname, 'img/so')); E:\ zf\ webpack\ 1\ src\ img\ so This is to splice file paths, regardless of whether the path actually exists.

console. log (path. resolve ('wwwroot', 'static_files/png/', '…/gif/image. gif')) E:\ zf\ webpack\ 1\ src\ wwwroot\ static_files\ gif\ image. gif

This is spliced with the absolute path of the current application startup file and all subsequent strings, because the initial string does not begin with/.

... is also for the top level 1 directory.


Related articles: