path.join and path.resolve Summary

1. connection path: path.join ([path1] [, path2] [, ...])
path.join () method can be any of a plurality of paths connecting strings. To connect multiple paths can be passed as a parameter. path.join () method will be normalized path while Edge path. E.g:

var path = require('path');
//合法的字符串连接
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// 连接后
'/foo/bar/baz/asdf'

//不合法的字符串将抛出异常
path.join('foo', {}, 'bar')
// 抛出的异常
TypeError: Arguments to path.join must be strings'

2. The path resolution: path.resolve ([from ...], to)
path.resolve () method of the plurality of paths may be resolved to an absolute path of a normalized. Which processes one by one in a manner similar cd operation of these paths, and cd operation is different, which causes the file path can be, and need not actually exist (Resolve () method does not use the underlying file system determines whether there is a path, and only a route string operations). E.g:

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')  
相当于
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

example:

path.resolve('/foo/bar', './baz')
// 输出结果为
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// 输出结果为
'/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// 当前的工作路径是 /home/itbilu/node,则输出结果为
'/home/itbilu/node/wwwroot/static_files/gif/image.gif' 

3. Comparison

const path = require('path');
let myPath = path.join(__dirname,'/img/so');
let myPath2 = path.join(__dirname,'./img/so');
let myPath3 = path.resolve(__dirname,'/img/so');
let myPath4 = path.resolve(__dirname,'./img/so');
console.log(__dirname);           //D:\myProgram\test
console.log(myPath);     //D:\myProgram\test\img\so
console.log(myPath2);   //D:\myProgram\test\img\so
console.log(myPath3);   //D:\img\so<br>
console.log(myPath4);   //D:\myProgram\test\img\so
  1. For at / path segments starting, path.join simply splicing the path segments, and will path.resolve / start root fragment as a path, the path will be discarded before, like in terminal use cd command.
path.join('/a', '/b') // 'a/b'
path.resolve('/a', '/b') // '/b'
  1. path.resolve always return an absolute path relative to the current working directory (working directory) is.
path.join('./a', './b') // 'a/b'
path.resolve('./a', './b') // '/Users/username/Projects/webpack-demo/a/b'

Guess you like

Origin blog.csdn.net/qq_27674439/article/details/92574857