
How to Get the Caller's Filename in Node.js
How to Get the Caller's Filename in Node.js There are situations — such as logging — where you want to know the name of the JavaScript file that called a function. The following code retrieves the filename of the JavaScript file that called hogehoge() : import path from ' path ' ; const hogehoge = () => { // Get the caller's filename const caller = path . basename ( new Error (). stack . split ( ' at ' )[ 2 ]. trim ()). split ( ' : ' )[ 0 ]; // Print to stdout console . log ( caller ); } Explanation Here's the same code broken down step by step: import path from ' path ' ; // Node.js Path Module const hogehoge = () => { // Get the caller's filename const stack = new Error (). stack ; // (1) Get the stack trace const lines = stack . split ( ' at ' ); // (2) Split by 'at' to get an array const line = lines [ 2 ]; // (3) Take the 3rd element (index 2) const trimed = line . trim (); // (4) Remove leading/trailing whitespace and newlines const basename = path . basename ( trimed ); // (5) S
Continue reading on Dev.to
Opens in a new tab



