内置的 path 模块能够在所有操作系统上正确地构建和操作文件路径。手动使用 / 拼接路径字符串在 Windows 上会失败(Windows 使用 \)并且无法正确处理边界情况 — path 能够可靠地处理所有这些。
// ❌ fragile, OS-dependent, error-prone
const filePath = baseDir + "/" + "sub" + "/" + fileName;
// breaks on Windows (\), doubles slashes if baseDir ends in /, etc.
import path from "path";
// ✅ uses the correct separator for the OS, normalizes slashes
const filePath = path.join(baseDir, "sub", fileName);
// Linux/Mac: baseDir/sub/file.txt Windows: baseDir\sub\file.txt
path.join 插入正确的分隔符、折叠重复/末尾斜杠,并解析 ../. 片段。
path.resolve("src", "app.js"); // → ABSOLUTE path from the cwd
path.basename("/a/b/file.txt"); // "file.txt"
path.dirname("/a/b/file.txt"); // "/a/b"
path.extname("file.txt"); // ".txt"
path.parse("/a/b/file.txt"); // { dir, base, name, ext }
path.sep; // "/" or "\" depending on OS
// CommonJS — built-in globals
const configPath = path.join(__dirname, "config.json");
// ES Modules — __dirname doesn't exist; derive it from import.meta.url
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
相对于当前文件构建路径(使用 __dirname 或其 ESM 等效项)是引用文件的安全方式 — 与进程的启动位置无关。
path.join → just joins segments (relative stays relative)
path.resolve → produces an ABSOLUTE path (resolves from cwd / right-to-left)
使用 path 而不是字符串拼接会使文件处理代码跨平台且健壮 — 这是一个常见的 bug 来源,当在 Mac/Linux 上编写的代码在 Windows 上崩溃,或当拼接产生格式错误的路径时。
这是一个小习惯,但能带来巨大的可靠性收益,了解 join vs resolve 以及如何在 ESM 中获取 __dirname,可以满足任何涉及文件系统的 Node 项目的日常路径需求。