js实现路径获取
获取当前文件路径
使用import.meta.url可以获取当前模块的完整URL路径,适用于ES模块环境。配合URL类可以转换为文件路径格式:
const currentPath = new URL(import.meta.url).pathname;
console.log('当前文件路径:', currentPath);
获取执行文件目录
通过process.argv[1]可以获取Node.js执行文件的绝对路径,结合path模块提取目录:

const path = require('path');
const dirname = path.dirname(process.argv[1]);
console.log('执行文件目录:', dirname);
解析路径组件
使用path.parse()方法分解路径为对象形式,包含root、dir、base等属性:
const parsed = path.parse('/home/user/file.txt');
console.log('路径分解:', parsed);
/*
{
root: '/',
dir: '/home/user',
base: 'file.txt',
ext: '.txt',
name: 'file'
}
*/
路径拼接操作
path.join()方法可跨平台拼接路径片段,自动处理分隔符:

const fullPath = path.join(__dirname, 'subdir', 'file.js');
console.log('拼接路径:', fullPath);
相对路径转换
path.relative()计算两个路径间的相对关系:
const relPath = path.relative('/a/b/c', '/a/d/e');
console.log('相对路径:', relPath); // 输出: ../../d/e
浏览器环境路径
浏览器中可通过window.location获取页面URL信息:
console.log('完整URL:', window.location.href);
console.log('路径部分:', window.location.pathname);






