js实现路径获取
获取当前页面路径
使用window.location对象可以获取当前页面的完整路径或部分路径信息。以下是常用属性:
const fullPath = window.location.href; // 完整URL(含协议、域名、路径等)
const pathname = window.location.pathname; // 路径部分(如"/articles/123")
const origin = window.location.origin; // 协议+域名(如"https://example.com")
获取文件绝对路径
通过URL.createObjectURL()可获取本地文件的临时路径:

const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
const filePath = URL.createObjectURL(file); // 生成blob路径
console.log(filePath); // 输出类似 blob:https://example.com/550e8400...
});
解析URL路径参数
使用URLSearchParams解析查询字符串:
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id'); // 获取?id=123中的123
const allParams = Object.fromEntries(urlParams.entries()); // 转为对象
Node.js路径处理
在Node.js环境中使用path模块处理文件路径:

const path = require('path');
const fullPath = path.join(__dirname, 'files', 'test.txt'); // 拼接路径
const ext = path.extname(fullPath); // 获取扩展名
const dir = path.dirname(fullPath); // 获取目录名
浏览器路由路径
前端框架中的路由路径获取示例(以React Router为例):
import { useLocation } from 'react-router-dom';
function Component() {
const location = useLocation();
console.log(location.pathname); // 获取当前路由路径
}
相对路径转绝对路径
将相对路径转换为绝对路径:
function toAbsoluteUrl(relativePath) {
return new URL(relativePath, window.location.origin).href;
}
const absUrl = toAbsoluteUrl('/images/logo.png');
以上方法覆盖了浏览器环境和Node.js环境下的常见路径获取需求,根据具体场景选择合适的方式即可。






