處理檔案路徑時,經常需要把一段相對路徑計算成絕對路徑。path.resolve 正是完成這件事的利器。
它會把參數 to 的位置解析到一個絕對路徑裡。
path.resolve([from ...], to)
由於屬於 path 模組,使用前需先引入:
var path = require("path");
path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
'/home/myself/node/wwwroot/static_files/gif/image.gif'
另一種理解方式,是把它看作一串依序執行的 cd 命令(shell):
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
相當於:
cd foo/bar cd /tmp/file/ cd .. cd a/../subfile pwd
從右到左依序處理,遇到以 / 開頭的段就會重置基準,最終計算出完整的絕對路徑。