path.basename()方法用於獲取文件路徑的文件名部分。使用此方法時,尾部目錄分隔符將被忽略。
用法:
path.basename( path, extension )
參數:此方法接受上述和以下所述的兩個參數:
- path:這是用於提取文件名的文件路徑。
- extension:它是一個可選的文件擴展名,將從返回的字符串中刪除。
返回值:它返回帶有路徑的文件名部分的字符串。如果路徑或擴展參數不是字符串值,則會引發錯誤。
以下示例程序旨在說明node.js中的path.basename()方法:
範例1:使用UNIX文件路徑
// Node.js program to demonstrate the
// path.basename() method
// Import the path module
const path = require('path');
path1 = path.basename('/home/user/bash/index.txt');
console.log(path1)
// Using the extension parameter
path2 = path.basename('/home/user/bash/index.txt', '.txt');
console.log(path2)
輸出:
index.txt index
範例2:使用Windows文件路徑
// Node.js program to demonstrate the
// path.basename() method
// Import the path module
const path = require('path');
path1 = path.basename('C:\\users\\bash\\index.html');
console.log(path1)
// Using the extension parameter
path2 = path.basename('C:\\users\\bash\\index.html', '.html');
console.log(path2)
輸出:
index.html index
參考: https://nodejs.org/docs/latest-v11.x/api/path.html#path_path_basename_path_ext
相關用法
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | path.basename() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。