path提供了一些用於處理文件與目錄的路徑工具,可以使用以下方式調用
const path = require("path");
path.basename() Method return path的最後一個部分。
const path = require("path");
const basename = path.basename("/foo/bar/baz/asdf/quux.html");
console.log(basename); //quux.html
const ext_basename = path.basename("/foo/bar/baz/asdf/quux.html",".html");
console.log(ext_basename); //quux
path.dirname() method return path的目錄名稱。
const path = require("path");
const dirname = path.dirname('/foo/bar/baz/asdf/quux');
console.log(dirname); ///foo/bar/baz/asdf
path.extname() Method return path的檔案類別名稱,從最後一次出現.(句點)字符到path最後一部分的字符串結束。如果在path的最後一部分中沒有.,或者如果path的基本名稱除了第一個字符以外沒有.,則返回空字符串。
const path = require("path");
const extname1 = path.extname("index.html");
console.log(extname1); //.html
const extname2 = path.extname("index.coffee.md");
console.log(extname2); //.md
const extname3 = path.extname("index.");
console.log(extname3); //.
path.format() Method 將輸入的Object組合成字串並return,與path.parse()相反。
const path = require("path");
coonst format = path.format({
dir : "C:\\path\\dir",
base: "file.txt"
);
console.log(format); //"C:\\path\\dir\\file.txt"
path.isAbsolute()方法檢測path是否為絕對路徑,如果給定的path是零長度字符串,則返回false。
const path = require("path");
const isAbsolute1 = path.isAbsolute("/foo/bar");
console.log(isAbsolute1); //true
const isAbsolute2 = path.isAbsolute("bar\\baz");
console.log(isAbsolute2); //false
path.join() Method 使用分隔符將所有給定的path連接在一起之後將組合的路徑return。
const path = require("path");
const join = path.join("/foo","bar","baz","asdf","quux.html");
console.log(join); //\foo\bar\baz\asdf\quux.html
path.parse() Method return 一個Object,其屬性表示path的重要元素。
const path = require("path");
const parse = path.parse("C:\\path\\dir\\file.txt");
console.log(parse); /*{
root: 'C:\\',
dir: 'C:\\path\\dir',
base: 'file.txt',
ext: '.txt',
name: 'file'
}*/
參考資料 :
path|Node.js