Node.js path 模块全部 API 详解
Node.js 的 path 模块提供了处理文件路径的工具函数,支持跨平台路径操作。以下是 path 模块的所有 API 详解:
1. 路径解析与操作
javascript
const path = require('path');
// 1. 路径连接
const fullPath = path.join(__dirname, 'files', 'data.json');
console.log('连接路径:', fullPath); // /当前目录/files/data.json
// 2. 路径解析
const pathObj = path.parse('/home/user/file.txt');
console.log('解析路径:', pathObj);
// {
// root: '/',
// dir: '/home/user',
// base: 'file.txt',
// ext: '.txt',
// name: 'file'
// }
// 3. 格式化路径对象
const pathString = path.format({
root: '/',
dir: '/home/user',
base: 'file.txt'
});
console.log('格式化路径:', pathString); // /home/user/file.txt
// 4. 获取文件名
const basename = path.basename('/path/to/file.txt'); // 'file.txt'
const basenameWithoutExt = path.basename('/path/to/file.txt', '.txt'); // 'file'
console.log('文件名:', basename);
console.log('无扩展名文件名:', basenameWithoutExt);
// 5. 获取目录名
const dirname = path.dirname('/path/to/file.txt'); // '/path/to'
console.log('目录名:', dirname);
// 6. 获取扩展名
const ext = path.extname('file.txt'); // '.txt'
console.log('扩展名:', ext);
// 7. 规范化路径
const normalized = path.normalize('/path/to/../file.txt'); // '/path/file.txt'
console.log('规范化路径:', normalized);
// 8. 解析相对路径
const resolved = path.resolve('relative/path', '../file.txt');
console.log('解析相对路径:', resolved);
// 9. 判断是否为绝对路径
const isAbsolute = path.isAbsolute('/path/to/file.txt'); // true
console.log('是否绝对路径:', isAbsolute);
// 10. 相对路径计算
const relative = path.relative('/path/to', '/path/to/file.txt'); // 'file.txt'
console.log('相对路径:', relative);
2. 平台特定路径
javascript
// 1. 获取路径分隔符
const sep = path.sep; // Windows: '\', POSIX: '/'
console.log('路径分隔符:', sep);
// 2. 获取路径定界符
const delimiter = path.delimiter; // Windows: ';', POSIX: ':'
console.log('路径定界符:', delimiter);
// 3. 获取平台特定路径
const posixPath = path.posix.join('a', 'b', 'c'); // 'a/b/c'
const win32Path = path.win32.join('a', 'b', 'c'); // 'a\b\c'
console.log('POSIX 路径:', posixPath);
console.log('Windows 路径:', win32Path);
3. 路径操作示例
javascript
// 1. 处理文件路径
function processFilePath(filePath) {
// 获取文件信息
const dir = path.dirname(filePath);
const base = path.basename(filePath);
const ext = path.extname(filePath);
const name = path.basename(filePath, ext);
// 构建新路径
const newPath = path.join(dir, `${name}_new${ext}`);
return {
directory: dir,
filename: base,
extension: ext,
name: name,
newPath: newPath
};
}
// 2. 处理相对路径
function resolveRelativePath(basePath, relativePath) {
return path.resolve(basePath, relativePath);
}
// 3. 检查文件类型
function isImageFile(filePath) {
const ext = path.extname(filePath).toLowerCase();
return ['.jpg', '.jpeg', '.png', '.gif', '.bmp'].includes(ext);
}
// 4. 构建 URL 路径
function buildUrlPath(baseUrl, ...paths) {
const urlPath = path.join(...paths).replace(/\\/g, '/');
return `${baseUrl}/${urlPath}`;
}
4. 跨平台路径处理
javascript
// 1. 统一路径格式
function normalizePath(filePath) {
// 将 Windows 路径转换为 POSIX 格式
return filePath.replace(/\\/g, '/');
}
// 2. 处理不同平台的路径
function getPlatformPath(filePath) {
if (process.platform === 'win32') {
return filePath.replace(/\//g, '\\');
}
return filePath;
}
// 3. 处理 URL 路径
function urlToFilePath(url) {
// 将 URL 转换为文件路径
const filePath = url.replace(/^file:\/\//, '');
return process.platform === 'win32'
? filePath.replace(/\//g, '\\')
: filePath;
}
5. 路径验证与清理
javascript
// 1. 验证路径
function isValidPath(filePath) {
// 检查路径是否包含非法字符
const invalidChars = /[<>:"|?*]/;
return !invalidChars.test(filePath);
}
// 2. 清理路径
function sanitizePath(filePath) {
// 移除非法字符
return filePath.replace(/[<>:"|?*]/g, '_');
}
// 3. 检查路径是否在允许的目录内
function isPathInAllowedDirectory(filePath, allowedDir) {
const resolvedPath = path.resolve(filePath);
const resolvedAllowedDir = path.resolve(allowedDir);
return resolvedPath.startsWith(resolvedAllowedDir);
}
6. 路径模块常量
javascript
// 1. 路径分隔符
console.log('路径分隔符:', path.sep); // Windows: '\', POSIX: '/'
// 2. 路径定界符
console.log('路径定界符:', path.delimiter); // Windows: ';', POSIX: ':'
// 3. 平台特定路径对象
console.log('POSIX 路径对象:', path.posix);
console.log('Windows 路径对象:', path.win32);
7. 实际应用示例
javascript
// 1. 文件上传路径处理
function handleFileUpload(originalFilename, uploadDir) {
// 获取文件扩展名
const ext = path.extname(originalFilename);
// 生成唯一文件名
const uniqueFilename = `${Date.now()}-${Math.random().toString(36).substring(2)}${ext}`;
// 构建完整路径
const filePath = path.join(uploadDir, uniqueFilename);
return {
originalFilename,
uniqueFilename,
filePath,
extension: ext
};
}
// 2. 配置文件路径处理
function getConfigPath(configName) {
// 获取用户主目录
const homeDir = process.env.HOME || process.env.USERPROFILE;
// 构建配置文件路径
const configDir = path.join(homeDir, '.myapp');
const configPath = path.join(configDir, `${configName}.json`);
return {
configDir,
configPath
};
}
// 3. 模块路径解析
function resolveModulePath(moduleName, baseDir) {
// 尝试解析模块路径
const modulePath = path.resolve(baseDir, 'node_modules', moduleName);
// 检查模块是否存在
const exists = require('fs').existsSync(modulePath);
return {
modulePath,
exists
};
}
8. 路径模块与其他模块结合
javascript
// 1. 与 fs 模块结合
const fs = require('fs');
function readConfigFile(configName) {
const { configPath } = getConfigPath(configName);
if (fs.existsSync(configPath)) {
return JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
return null;
}
// 2. 与 url 模块结合
const url = require('url');
function fileUrlToPath(fileUrl) {
const filePath = url.fileURLToPath(fileUrl);
return path.resolve(filePath);
}
// 3. 与 glob 模块结合
const glob = require('glob');
function findFiles(pattern, baseDir) {
const fullPattern = path.join(baseDir, pattern);
return glob.sync(fullPattern);
}
path 模块的主要特点:
- 提供跨平台路径操作
- 支持路径解析和格式化
- 提供路径组件提取
- 支持相对路径和绝对路径转换
- 提供平台特定路径处理
使用建议:
- 使用
path.join()
而不是字符串拼接来连接路径 - 使用
path.resolve()
处理相对路径 - 使用
path.normalize()
清理路径 - 注意跨平台兼容性
- 使用
path.basename()
和path.extname()
提取文件名和扩展名