path.extname()方法用於獲取文件路徑的擴展部分。擴展字符串從路徑中最後一次出現的句點(。)返回到路徑字符串的末尾。如果文件路徑中沒有句點,則返回一個空字符串。
用法:
path.extname( path )
參數:此方法接受單個參數路徑,該路徑包含用於提取擴展名的文件路徑。
返回值:它返回帶有路徑擴展部分的字符串。如果此參數不是字符串值,則拋出TypeError。
以下示例說明了node.js中的path.extname()方法:
範例1:
// Node.js program to demonstrate the
// path.extname() method
// Import the path module
const path = require('path');
path1 = path.extname("hello.txt");
console.log(path1)
path2 = path.extname("readme.md");
console.log(path2)
// File with no extension
// Returns empty string
path3 = path.extname("fileDump")
console.log(path3)
// File with blank extension
// Return only the period
path4 = path.extname("example.")
console.log(path4)
path5 = path.extname("readme.md.txt")
console.log(path5)
// Extension name of the current script
path6 = path.extname(__filename)
console.log(path6)
輸出:
.txt .md . .txt .js
範例2:
// Node.js program to demonstrate the
// path.extname() method
// Import the path module
const path = require('path');
// Comparing extensions from a
// list of file paths
paths_array = [
"/home/user/website/index.html",
"/home/user/website/style.css",
"/home/user/website/bootstrap.css",
"/home/user/website/main.js",
"/home/user/website/contact_us.html",
"/home/user/website/services.html",
]
paths_array.forEach(filePath => {
if (path.extname(filePath) == ".html")
console.log(filePath);
});
輸出:
/home/user/website/index.html /home/user/website/contact_us.html /home/user/website/services.html
參考: https://nodejs.org/api/path.html#path_path_extname_path
相關用法
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | path.extname() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。