js实现路径获取
获取当前脚本路径
在JavaScript中获取当前执行的脚本路径可以通过document.currentScript属性实现。该属性返回当前正在执行的<script>元素:
const currentScriptPath = document.currentScript.src;
console.log('当前脚本路径:', currentScriptPath);
注意:该方法仅在脚本同步执行时有效,异步加载的脚本可能返回null。
获取调用栈中的路径
通过new Error().stack可以获取调用栈信息,从中提取文件路径:
function getScriptPath() {
const stack = new Error().stack;
const stackLines = stack.split('\n');
// 通常第二行包含调用者信息
const callerLine = stackLines[2];
const match = callerLine.match(/(http|https|file):\/\/[^)]+/);
return match ? match[0] : null;
}
const path = getScriptPath();
console.log('调用栈路径:', path);
动态加载脚本路径
对于动态创建的<script>标签,可以在加载事件中获取路径:
const script = document.createElement('script');
script.src = 'example.js';
script.onload = function() {
console.log('加载的脚本路径:', this.src);
};
document.head.appendChild(script);
Node.js环境路径获取
在Node.js环境中可以使用__filename和__dirname获取路径:
console.log('当前文件绝对路径:', __filename);
console.log('当前目录路径:', __dirname);
// 获取调用者路径
const callerPath = require.cache[module.parent.id].filename;
console.log('调用者路径:', callerPath);
相对路径转换为绝对路径
将相对路径转换为绝对路径可以使用URL API:
const relativePath = './lib/utils.js';
const absolutePath = new URL(relativePath, window.location.href).href;
console.log('绝对路径:', absolutePath);
获取页面基础路径
通过document.baseURI获取文档的基础路径:
const basePath = document.baseURI;
console.log('文档基础路径:', basePath);
路径解析与操作
使用URL对象可以方便地解析和操作路径:

const url = new URL('https://example.com/path/file.html?query=1');
console.log('协议:', url.protocol);
console.log('主机:', url.host);
console.log('路径:', url.pathname);
console.log('文件名:', url.pathname.split('/').pop());






