Zi 字媒體
2017-07-25T20:27:27+00:00
此篇文章瀏覽量:
884
在已知的一個相對路徑的時候,可以透過 path.resolve(path) 方法,將它解析成絕對路徑。
而使用 path.relative(from, to) 方法,可以將兩個絕對路徑取得相對路徑。
使用 path.resolve(path) 將相對路徑解析成絕對路徑
var path = require('path'); // 引入路徑處理模組
console.info(process.cwd());
// 輸出結果:/Users/carlos/Documents/test
var path_a = "./txt/ch09.path_resolve.js";
console.info(path.resolve(path_a));
// 輸出結果:/Users/carlos/Documents/test/txt/ch09.path_resolve.js
var path_b = "other"; // other 是一個自己建的目錄
var path_c = "other.txt"; // other.txt 建立好後,存放於 other 資料夾
console.info(path.resolve(path_b, path_c));
// 輸出結果:/Users/carlos/Documents/test/other/other.txt
使用 path.relative(from, to) 將兩個字串絕對路徑,取得相對路徑
var path = require('path'); // 引入路徑處理模組
var path_a = "path_relative.js";
var path_resolve_a = path.dirname(path.resolve(path_a));
var path_b = "txt/watchFile.txt";
var path_resolve_b = path.dirname(path.resolve(path_b));
console.log(path_resolve_a);
// 輸出結果:/Users/carlos/Documents/test
console.log(path_resolve_b);
// 輸出結果:/Users/carlos/Documents/test/txt
console.info( path.relative(path_resolve_a, path_resolve_b) );
// 輸出結果:txt
關於 path.relative(from, to) 使用說明,請參考官網,from 跟 to 需為資料夾的路徑較正確。
若覺得文章有幫助,請多分享,讓其他同好也能吸收網站技能知識。
Facebook
Twitter
寫了
5860316篇文章,獲得
23313次喜歡