Get the path of the caller function
npx @tessl/cli install tessl/npm-caller-path@4.0.0Caller Path is a lightweight utility library that gets the file path of the calling function in JavaScript. It provides a simple API for determining the source location of function calls, which is useful for debugging, logging, and development tooling scenarios where you need to programmatically identify the source location of code execution.
npm install caller-pathimport callerPath from "caller-path";Note: This package is ESM-only and does not support CommonJS require().
import callerPath from "caller-path";
// foo.js
export default function foo() {
console.log(callerPath());
//=> '/Users/username/project/bar.js'
}
// bar.js
import foo from './foo.js';
foo(); // This will print the path to bar.jsGets the file path of the calling function with optional depth traversal to go back multiple levels in the call stack.
/**
* Get the path of the caller function
* @param options - Configuration options
* @returns The file path of the caller, or undefined if unable to determine
*/
function callerPath(options?: Options): string | undefined;
interface Options {
/**
* The caller path depth, meaning how many levels we follow back on the stack trace
* @default 0
*/
readonly depth?: number;
}Usage Examples:
import callerPath from "caller-path";
// Basic usage - get immediate caller
function logCaller() {
console.log(callerPath());
//=> '/path/to/calling/file.js'
}
// With depth parameter - traverse call stack
function deepFunction() {
console.log(callerPath()); // depth 0 - immediate caller
console.log(callerPath({depth: 1})); // depth 1 - one level back
console.log(callerPath({depth: 2})); // depth 2 - two levels back
}
// Example call stack traversal:
// foo.js calls bar.js calls baz.js calls deepFunction()
// depth: 0 => baz.js
// depth: 1 => bar.js
// depth: 2 => foo.jsError Handling:
The function returns undefined if the caller's callsite object getFileName is not defined for some reason, such as:
Stack Trace Depth:
The depth parameter controls how many levels to traverse back in the call stack:
depth: 0 (default): Returns the immediate caller's file pathdepth: 1: Returns the caller of the caller's file pathdepth: 2: Returns two levels back in the call stackThis is particularly useful in wrapper functions or middleware where you need to identify the original source of a call rather than just the immediate wrapper.