路徑操作
在 Github 上編輯
許多應用程式需要以某種方式操作檔案路徑。Deno 標準函式庫提供了用於此目的的簡單工具。
首先,我們將從 Deno 標準函式庫匯入模組
import * as path from "jsr:@std/path";
import * as posix from "jsr:@std/path/posix";
import * as windows from "jsr:@std/path/windows";
從檔案 URL 轉換為目錄可以透過適當實作中的 `fromFileUrl` 方法簡單完成。
const p1 = posix.fromFileUrl("file:///home/foo");
const p2 = windows.fromFileUrl("file:///home/foo");
console.log(`Path 1: ${p1} Path 2: ${p2}`);
我們也可以選擇不指定平台,並自動使用 Deno 正在運行的任何平台
const p3 = path.fromFileUrl("file:///home/foo");
console.log(`Path on current OS: ${p3}`);
我們可以使用 basename 方法取得檔案路徑的最後一部分
const p = path.basename("./deno/is/awesome/mod.ts");
console.log(p); // mod.ts
我們可以使用 dirname 方法取得檔案路徑的目錄
const base = path.dirname("./deno/is/awesome/mod.ts");
console.log(base); // ./deno/is/awesome
我們可以使用 extname 方法取得檔案路徑的副檔名
const ext = path.extname("./deno/is/awesome/mod.ts");
console.log(ext); // .ts
我們可以使用 FormatInputPathObject 格式化路徑
const formatPath = path.format({
root: "/",
dir: "/home/user/dir",
ext: ".html",
name: "index",
});
console.log(formatPath); // "/home/user/dir/index.html"
當我們想要使程式碼跨平台時,可以使用 join 方法。這會使用作業系統特定的檔案分隔符號連接任意數量的字串。在 Mac OS 上,這會是 foo/bar。在 Windows 上,這會是 foo\bar。
const joinPath = path.join("foo", "bar");
console.log(joinPath);
我們可以使用內建的 cwd 方法取得目前的工作目錄
const current = Deno.cwd();
console.log(current);
使用 Deno CLI 在本機執行此範例
deno run --allow-read https://deno-docs.dev.org.tw/examples/scripts/path_operations.ts