node.js之path常用方法

node.js之path常用方法

1.path.join([...paths])

用于将多个路径片段拼接成一个路径,会自动处理路径分隔符,避免手动拼接时可能出现的问题

复制代码
const joinedPath = path.join('folder1', 'folder2', 'file.txt');
console.log(joinedPath); 
// 输出: folder1/folder2/file.txt
2. path.resolve([...paths])

将路径或路径片段解析为绝对路径,从右到左处理路径片段,直到构建出一个绝对路径

复制代码
const resolvedPath = path.resolve('folder1', 'folder2', 'file.txt');
console.log(resolvedPath); 
// 假设当前工作目录是 /home/user,输出: /home/user/folder1/folder2/file.txt
3. path.basename(path[.ext])

返回路径的最后一部分,即文件名。可以选择性地传入文件扩展名,以去除该扩展名

复制代码
const filePath = '/home/user/folder/file.txt';
const baseName = path.basename(filePath);
console.log(baseName); 
// 输出: file.txt

const baseNameWithoutExt = path.basename(filePath, '.txt');
console.log(baseNameWithoutExt); 
// 输出: file
4.path.dirname(path)

返回路径的目录部分,即去除文件名后的路径

复制代码
const filePath = '/home/user/folder/file.txt';
const dirName = path.dirname(filePath);
console.log(dirName); 
// 输出: /home/user/folder
5.path.extname(path)

返回路径的文件扩展名,包括点号

复制代码
const filePath = '/home/user/folder/file.txt';
const extName = path.extname(filePath);
console.log(extName); 
// 输出: .txt
6. path.parse(path)

将路径解析为一个对象,包含根目录、目录、文件名、扩展名等信息

复制代码
const filePath = '/home/user/folder/file.txt';
const pathObject = path.parse(filePath);
console.log(pathObject); 
// 输出: { root: '/', dir: '/home/user/folder', base: 'file.txt', ext: '.txt', name: 'file' }
7.path.format(pathObject)

将一个路径对象转换为路径字符串,是 path.parse() 的反向操作

复制代码
const pathObject = {
    root: '/',
    dir: '/home/user/folder',
    base: 'file.txt',
    ext: '.txt',
    name: 'file'
};
const formattedPath = path.format(pathObject);
console.log(formattedPath); 
// 输出: /home/user/folder/file.txt
相关推荐
蛊明1 小时前
Win11 如何下载安装 Node.js
node.js
Bruce12320 小时前
openclaw学习日常(一)openclaw在WSL中搭建
人工智能·node.js
Hommy881 天前
【开源剪映小助手-客户端】桌面客户端
python·开源·node.js·github·剪映小助手
走粥1 天前
node.js 中的 express 框架 - 基础到进阶
node.js·express
qq_229058011 天前
使用nvm安装node12 以及对应的NPM6.14.16
node.js
zhensherlock1 天前
Protocol Launcher 系列:Mail Assistant 轻松发送 HTML 邮件
前端·javascript·typescript·node.js·html·github·js
旺王雪饼 www1 天前
《Express框架深度解析:从基础入门到高级实践与项目架构》
前端·node.js·express
星光不问赶路人2 天前
Node.js 如何判断入口文件:从 require.main 到 ES Module 实现
前端·node.js
网络点点滴2 天前
Node.js 中阻塞、非阻塞及异步特性
node.js