如果你需要的调用者文件没有在实现它的文件中被调用——就像在 OP 的场景中一样——你可以写:
function _getCallerFile()
{
const prepareStackTraceOrg = Error.prepareStackTrace;
const err = new Error();
Error.prepareStackTrace = (_, stack) => stack;
const stack = err.stack;
Error.prepareStackTrace = prepareStackTraceOrg;
return stack[1].getFileName();
}
try...catch 是不必要的,因为如果将 Error 分配给变量,则不会抛出它。
此外,如果您想在多个项目中使用_getCallerFile,您可能希望将它放在自己的文件中,但随后您将获得调用_getCallerFile 的文件的名称。
在这种情况下,只需写return stack[2].getFileName();,即。 e.在调用堆栈中再退一步。
如果您使用 TypeScript,则必须编写 const stack = err.stack as unknown as NodeJS.CallSite[];,因为 Error.stack 的声明类型是 string,但我们的 prepareStackTrace 函数返回一个 NodeJS.CallSite 对象数组。
仅供参考:NodeJS.CallSite 有更多有趣的方法,例如。 G。 getFunctionName.
更新
在分配 lambda 之前,我注意到 Error.prepareStackTrace === undefined。如果您不信任我,只需将console.log('prepareStackTraceOrg:', prepareStackTraceOrg); 添加到函数中即可。
因此,我们可以简化函数:
function _getCallerFile()
{
const err = new Error();
Error.prepareStackTrace = (_, stack) => stack;
const stack = err.stack;
Error.prepareStackTrace = undefined;
return stack[1].getFileName();
}