温馨提示×

dirname如何处理相对路径

小樊
82
2024-06-29 15:40:40
栏目: 编程语言

在 Node.js 中,dirname 方法用于获取指定路径的父目录路径。当传入相对路径时,dirname 方法会将相对路径解析为绝对路径,然后返回父目录路径。

例如,假设当前工作目录为 /home/user/project,如果传入相对路径 ./folder/file.jsdirname 方法会返回 /home/user/project/folder

以下是一个示例代码:

const path = require('path');

const relativePath = './folder/file.js';
const absolutePath = path.resolve(relativePath);
const parentDir = path.dirname(absolutePath);

console.log(parentDir); // 输出 /home/user/project/folder

在处理相对路径时,建议始终使用path.resolve()方法将其转换为绝对路径,以确保路径处理的准确性。

0