CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-get-caller-file

A utility function to determine which file called a function by inspecting v8's stack trace

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Get Caller File

Get Caller File is a lightweight TypeScript utility that determines which file called a function by inspecting Node.js/V8's stack trace at runtime. It provides a simple API for call stack analysis, making it useful for debugging, logging systems, error reporting, and development tools that need to track function call origins.

Package Information

  • Package Name: get-caller-file
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install get-caller-file

Core Imports

For TypeScript with CommonJS module syntax:

import getCallerFile = require("get-caller-file");

For CommonJS:

const getCallerFile = require("get-caller-file");

Basic Usage

const getCallerFile = require("get-caller-file");

function myFunction() {
  const callerFile = getCallerFile();
  console.log(`Called from: ${callerFile}`);
}

// In another file (e.g., app.js)
myFunction(); // Logs: "Called from: /path/to/app.js"

Capabilities

Stack Trace Analysis

Determines which file called a function by inspecting the V8 stack trace at a specified position.

/**
 * Determines which file called this function by inspecting V8 stack trace
 * @param position - Stack frame position to examine (default: 2)
 * @returns Full file path of the calling file, or undefined if frame doesn't exist
 * @throws TypeError when position >= Error.stackTraceLimit
 */
function getCallerFile(position?: number): string | undefined;

Parameters:

  • position (optional): number - Stack frame position to examine
    • 0: Current file (where getCallerFile is defined)
    • 1: File where getCallerFile was called
    • 2: File that called the function containing getCallerFile (default behavior)
    • Higher numbers: Further up the call stack

Return Value:

  • string: Full file path of the calling file
  • undefined: If stack frame at specified position doesn't exist

Exceptions:

  • TypeError: Thrown when position >= Error.stackTraceLimit
  • Error message format: "getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: \{position}` and Error.stackTraceLimit was: `{limit}`"`

Usage Examples:

const getCallerFile = require("get-caller-file");

// Default behavior - get the file that called the function containing getCallerFile
function logger(message) {
  const callerFile = getCallerFile(); // position = 2 (default)
  console.log(`[${callerFile}] ${message}`);
}

// Custom stack position - look further up the call stack
function deepLogger(message) {
  const callerFile = getCallerFile(3); // Look 3 frames up
  console.log(`[${callerFile}] ${message}`);
}

// Error handling for stack limit overflow
function safeGetCaller(position) {
  try {
    return getCallerFile(position);
  } catch (error) {
    if (error instanceof TypeError) {
      console.error("Stack position out of bounds:", error.message);
      return null;
    }
    throw error;
  }
}

Call Stack Positions:

// Example call stack breakdown:
// File: /app/utils/logger.js
function createLogger() {
  return function log(message) {
    // Position 0: /node_modules/get-caller-file/index.js (getCallerFile definition)
    // Position 1: /app/utils/logger.js (this function - where getCallerFile is called)
    // Position 2: /app/services/auth.js (file that called log function) ← default
    // Position 3: /app/controllers/user.js (file that called auth service)
    const caller = getCallerFile(); // Returns /app/services/auth.js
    console.log(`[${caller}] ${message}`);
  };
}

// File: /app/services/auth.js
const log = createLogger();
log("Authentication successful"); // getCallerFile() returns this file path

// File: /app/controllers/user.js
// (calls auth service, which calls log function)

Platform Requirements

Node.js/V8 Compatibility:

  • Requires Node.js 6.* || 8.* || >= 10.*
  • Uses V8-specific Error.prepareStackTrace API
  • Not compatible with other JavaScript runtimes (browsers, Deno, etc.)

Stack Trace Dependencies:

  • Relies on Error.stackTraceLimit being sufficient for the requested position
  • Uses runtime stack inspection which may have performance implications for high-frequency calls
  • Stack trace format and availability may vary between Node.js versions

Error Handling

The function throws a TypeError when the requested stack position exceeds the current Error.stackTraceLimit. Always handle this case when using custom positions:

function robustGetCaller(position = 2) {
  const originalLimit = Error.stackTraceLimit;
  
  try {
    // Ensure stack trace limit is sufficient
    if (position >= Error.stackTraceLimit) {
      Error.stackTraceLimit = position + 5; // Add buffer
    }
    
    return getCallerFile(position);
  } catch (error) {
    if (error instanceof TypeError && error.message.includes('stackTraceLimit')) {
      console.warn('Cannot determine caller: stack position out of bounds');
      return null;
    }
    throw error;
  } finally {
    Error.stackTraceLimit = originalLimit; // Restore original limit
  }
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/get-caller-file@2.0.x
Publish Source
CLI
Badge
tessl/npm-get-caller-file badge