Home > other >  How to get the current module's file path in a node module?
How to get the current module's file path in a node module?

Time:05-27

I want to print the correct filepath even if the function is imported in some other module inorder to handle the errors correctly. 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,

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,

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

When there occurs an error while connecting to DB, then It prints something like this,

2022-05-27T05:24:47.548Z src/test.ts: Error in connecting DB url is unreachable please check your internet 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.

CodePudding user response:

Try changing the logger class using this like @zyp suggested.

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

CodePudding user response:

Try using

__filename

__filename: This will return the path of the file executing

__dirname: This will return the path of the directory in which the file executing is located.

Check if it does what you need like

console.log(__filename);

CodePudding user response:

Try to change filePath to this.filePath in your Logger Class

  • Related