如何获取当前模块在节点模块中的文件路径?

问题描述 投票:0回答:3

即使该函数被导入到其他模块中,我也想打印正确的文件路径,以便正确处理错误。我怎样才能做到这一点?我正在使用无服务器堆栈。

请参考以下代码,

class Logger {
  filePath: string;
  
  constructor(fp: string) {
    filePath = fp;
  }
  
  printLog(info) {
    const { timestamp, message } = info;
    
    return `${timestamp} ${filePath}: ${message}`;
  }
}

这在

dbConnection.ts
中使用为,

const logger = new Logger(__filename);

export const connectToDB = () => {
  try {
    //DB connection code.
  } catch(error) {
    logger.print({ timestamp: new Date().toISOString(), message: error.message });
  }
};

现在,我想从其他模块连接到数据库,

test.ts
然后我将按如下方式使用它,

export const test = () => {
  //some code here...
  
  connectToDB();
  
}

当连接到数据库时发生错误时,它会打印类似这样的内容,

2022-05-27T05:24:47.548Z src/test.ts: Error in connecting DB url is unreachable please check your internet connection.

为了具有适当的可调试性,我想打印实际引发异常的文件名。那是

src/dbConnection.ts
而不是
src/test.ts

javascript node.js typescript webpack ecmascript-6
3个回答
0
投票

如果在模块中:

console.log(import.meta.url)

在浏览器中工作,不确定是否可以用于节点导入。


-2
投票

尝试使用

__filename

__filename
:这将返回文件执行的路径

__dirname
:这将返回执行文件所在目录的路径。

检查它是否满足您的需要

console.log(__filename);

-3
投票

尝试将 Logger 类中的

filePath
更改为
this.filePath

© www.soinside.com 2019 - 2024. All rights reserved.