温馨提示×

dirname如何处理相对路径

小樊
87
2024-06-29 15:40:40
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 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()方法将其转换为绝对路径,以确保路径处理的准确性。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何使用dirname函数处理相对路径和绝对路径

0