javascript - Get path of file which executed another file
问题描述
I would like to get the path of the file which executed another file.
first.js
const second = require("./second.js");
exports.run = () => {
second.run();
}
second.js
exports.run = () => {
let executedPath; // <-- ?
console.log(`File which executed this function: ${executedPath}`);
}
If you throw an error in the function (throw new Error("test")
) the console shows the following:
UnhandledPromiseRejectionWarning: Error: test
at exports.run (/test/two.js:5:9)
at exports.run.<anonymous> (/test/one.js:5:8)
So I guess it knows which file executed second.js
but how to get the path of it?
解决方案
You can dig the value out of new Error().stack
along these lines:
function executedPath(n) {
return new Error().
stack.
split('\n')[n+1].
match(/\(([^\)]*):\d+:\d+\)/)[1]
}
推荐阅读
- matlab - Matlab 并行运行时看不到特定函数
- c++ - 为什么 make_shared 比 shared_ptr 慢
(新T) - php - get_results("select * from table_name where id IN($array)") 但它假定 $array 为 "Array"
- arrays - 使用ajax将字节数组对象发送到控制器
- python - 来自数组元素python的抛物线
- docker - aspnetcore-runtime:从 microsoft/dotnet 中提取清单列表条目中的 windows/amd64 10.0.17134 没有匹配的清单
- java - 针对 Android API < 26 时,Duration.between 的最佳替代方案是什么?
- android - 如何找出编译的 Cordova 应用程序中使用的依赖项版本?
- elasticsearch - 有没有办法在一段时间内自动导出 kibana 可视化数据?
- vhdl - 通过重复加法乘数