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
相关推荐
竹林8183 小时前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js
oyzz12011 小时前
Windows 上彻底卸载 Node.js
windows·node.js
小霍同学11 小时前
Node.js 起步指南
node.js
codingWhat12 小时前
用 Express 简单Mock自助终端机读取身份证
node.js·express
回到原点的码农12 小时前
TypeScript 与后端开发Node.js
javascript·typescript·node.js
skiy13 小时前
Webpack、Vite区别知多少?
前端·webpack·node.js
橙露1 天前
Webpack/Vite 打包优化:打包体积减半、速度翻倍
前端·webpack·node.js
十五年专注C++开发1 天前
libuv:一个跨平台的C++异步 I/O 库
开发语言·c++·node.js·libuv·vlibuv
困惑阿三1 天前
客户消息及时反馈
nginx·node.js·飞书·企业微信
饥饿的帕尼尼1 天前
Claude Code本地安装使用教程
node.js·github·claude