[英]How to get the current module's file path in a node module?
I want to print the correct filepath even if the function is imported in some other module inorder to handle the errors correctly.即使在其他模块中导入了 function 以便正确处理错误,我也想打印正确的文件路径。 How can I do that?
我怎样才能做到这一点? I am using serverless stack.
我正在使用无服务器堆栈。
Please refer the following code,请参考以下代码,
class Logger { filePath: string; constructor(fp: string) { filePath = fp; } printLog(info) { const { timestamp, message } = info; return `${timestamp} ${filePath}: ${message}`; } }
This is used in dbConnection.ts
as,这在
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 }); } };
Now, I want to connect to db from some other module lets say, test.ts
then I will use it as follows,现在,我想从其他模块连接到数据库,比如
test.ts
然后我将按如下方式使用它,
export const test = () => { //some code here... connectToDB(); }
When there occurs an error while connecting to DB, then It prints something like this,当连接到 DB 时发生错误,然后它会打印如下内容,
2022-05-27T05:24:47.548Z src/test.ts: Error in connecting DB url is unreachable please check your inte.net connection.
In order to have proper debuggability, I want to print the filename from where the exception is actually thrown.为了具有适当的可调试性,我想从实际抛出异常的地方打印文件名。 That is
src/dbConnection.ts
and not src/test.ts
.那是
src/dbConnection.ts
而不是src/test.ts
。
Try using尝试使用
__filename
__filename
: This will return the path of the file executing __filename
:这将返回执行文件的路径
__dirname
: This will return the path of the directory in which the file executing is located. __dirname
:这将返回执行文件所在目录的路径。
Check if it does what you need like检查它是否满足您的需求
console.log(__filename);
Try to change filePath
to this.filePath
in your Logger Class尝试在记录器 Class 中将文件
this.filePath
更改为filePath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.