deno.com

路径操作

在 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";
通过适当实现中的 `fromFileUrl` 方法,可以简单地将文件 URL 转换为目录。
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://docs.deno.org.cn/examples/scripts/path_operations.ts

您找到所需的内容了吗?

隐私政策