即使该函数被导入到其他模块中,我也想打印正确的文件路径,以便正确处理错误。我怎样才能做到这一点?我正在使用无服务器堆栈。
请参考以下代码,
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
。
如果在模块中:
console.log(import.meta.url)
在浏览器中工作,不确定是否可以用于节点导入。
尝试使用
__filename
__filename
:这将返回文件执行的路径
__dirname
:这将返回执行文件所在目录的路径。
检查它是否满足您的需要
console.log(__filename);
尝试将 Logger 类中的
filePath
更改为 this.filePath