[英]Get current working directory name instead of path in Node.js
我正在開發一個需要使用當前目錄名稱的 CLI 應用程序。
我可以使用process.cwd()
獲取當前目錄的路徑。 如何獲取當前目錄名稱而不是整個路徑?
可以執行以下操作嗎?
process.cwd().split('/').slice(-1)[0]
它有效,但感覺很脆弱。 這樣做的最佳和最強大的方法是什么?
即使答案中的代碼有效,您也應該使用path.basename()
來獲取路徑最后一部分的名稱,因為:
/
在/path/to/cwd/
) 此外,為了額外的安全,您應該使用path.resolve()
因為它在獲取基本名稱之前規范化路徑,擺脫與路徑相關的怪癖。
如果您可以使用process.cwd()
獲取/path/to/cwd
,那么以下內容將為您提供目錄的名稱(示例中的"cwd"
):
path.basename(process.cwd())
添加path.resolve()
以提高安全性:
path.basename(path.resolve(process.cwd()))
甚至:
path.basename(path.resolve())
const path = require('path');
function slice(pathName) {
const res = pathName.split(path.sep).slice(-1)[0];
console.log('slicer ', pathName, '=>', `'${res}'`);
}
function basename(pathName) {
const res = path.basename(path.resolve(pathName));
console.log('basename', pathName, '=>', `'${res}'`);
}
slice('/path/to/cwd'); // cwd
basename('/path/to/cwd'); // cwd
slice('/path/to/cwd/'); // ''
basename('/path/to/cwd/'); // cwd
// Other valid paths
slice('/path/to/cwd/..'); // '..'
basename('path/to/cwd/..'); // cwd
slice('.'); // '.'
basename('.'); // <current directory name>
Returns: <string>
process.cwd() 方法返回 Node.js 進程的當前工作目錄。
console.log(`Current directory: ${process.cwd()}`);
這保證是當前工作目錄的絕對路徑。 用這個!
path <string>
ext <string> An optional file extension
Returns: <string>
path.basename()
方法返回路徑的最后一部分,類似於 Unix basename 命令。 尾隨目錄分隔符將被忽略,請參見 path.sep。path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html'); // Returns: 'quux'
如果 path 不是字符串或者 ext 不是字符串,則拋出 TypeError 。
...paths <string> A sequence of paths or path segments Returns: <string>
path.resolve() 方法將一系列路徑或路徑段解析為絕對路徑。
給定的路徑序列從右到左處理,每個后續路徑都在前面,直到構建絕對路徑。 例如,給定路徑段的序列:/foo, /bar, baz,調用 path.resolve('/foo', '/bar', 'baz') 將返回 /bar/baz。
如果在處理完所有給定的路徑段后還沒有生成絕對路徑,則使用當前工作目錄。
生成的路徑被規范化並刪除尾部斜杠,除非路徑解析為根目錄。
零長度路徑段被忽略。
如果沒有傳遞路徑段, path.resolve() 將返回當前工作目錄的絕對路徑。
如果你可以使用process.cwd()
你不需要path.resolve()
在其他情況下,使用它!。
您正在尋找path.basename :
const path = require('path');
path.basename(CWD)
path.basename()方法返回路徑的最后一部分。 尾隨目錄分隔符被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.