關於path.join,path.resolve的詳細介紹

vue-cli生成的webpack配置中有大量path.resolve,path.join,有些模糊。網上查了很久,終於發現一篇講的比較全面的文章vue

如下是原文:node

1.鏈接路徑:path.join([path1][, path2][, ...])
path.join()方法能夠鏈接任意多個路徑字符串。要鏈接的多個路徑可作爲參數傳入。webpack

path.join()方法在接邊路徑的同時也會對路徑進行規範化。例如:web

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.路徑解析:path.resolve([from ...], to)
path.resolve()方法能夠將多個路徑解析爲一個規範化的絕對路徑。其處理方式相似於對這些路徑逐一進行cd操做,與cd操做不一樣的是,這引發路徑能夠是文件,而且可沒必要實際存在(resolve()方法不會利用底層的文件系統判斷路徑是否存在,而只是進行路徑字符串操做)。例如:vue-cli

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

至關於ui

cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

例子:code

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.對比字符串

const path = require('path'); 
let myPath = path.join(__dirname,'/img/so'); //D:\myProgram\test\img\so 
let myPath2 = path.join(__dirname,'./img/so'); //D:\myProgram\test\img\so 
let myPath3 = path.resolve(__dirname,'/img/so'); // D:\img\so
let myPath4 = path.resolve(__dirname,'./img/so'); // D:\myProgram\test\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
相關文章
相關標籤/搜索