node 是有一個 path 的 package,但這個 package 會依賴 process 來取得平台環境,以決定要用 win32 或是 posix 來處理路徑。
但我其實只是要簡單的取得父路徑跟從路徑取出檔案或目錄名稱,不需要這樣麻煩。上網找到這篇:Javascript functions for basename and dirname 。它的實作是使用 regular expression 來處理,所以傳回的並不是單純的字串,而是一個陣列 RegExMatchArray 。參考 MDN 的 String.prototype.match() 來做調整,簡單的說,陣列的第一個元素就是處理的結果,所以只要先判斷傳回值是否為 null ,然後再傳回第一個元素即可。
// Typescript
/**
* 取得父路徑
*/
export function dirname(path: string): string {
let newPath = '';
// 找符合 '/aaa/bbb/ccc/' 的字串
const regExMatchArray = path.match(/.*\//);
// 沒有找到,傳回 '/'
if (regExMatchArray === null ) {
newPath = '/';
}
else {
// 有找到
newPath = regExMatchArray[0];
// 看最後字元是否為 '/',是的話,就移除。
if (newPath.endsWith('/')) {
newPath = newPath.substring(0, newPath.length - 1);
}
// 最後結果的長度為0,加上 '/'
if (newPath.length === 0) {
newPath = '/';
}
}
return newPath;
}
/**
* 取得檔名或目錄名
*/
export function basename(path: string): string {
// 把 '/' (含)之前的字元都替換成空字串
return path.replace(/.*\//, '');
}