Get Caller File Path

2.0.5 · active · verified Tue Apr 21

get-caller-file is a specialized Node.js utility designed to programmatically determine the file path from which a given function was invoked. It achieves this by inspecting the V8 JavaScript engine's call stack at the point of invocation. The package is currently at version 2.0.5, with its development pace typically tied to the stability of V8's stack trace API, implying a generally stable but infrequent release cadence as the core functionality is mature. A key differentiator is its direct reliance on Node.js and V8-specific APIs, making it highly effective within its intended environment but explicitly unsuitable for other JavaScript runtimes like web browsers or non-V8 environments. This constraint is crucial for developers to note, as attempting to use it outside of Node.js will lead to unexpected behavior or errors. It serves a niche but critical role in scenarios requiring introspection into the call stack for debugging, logging, or module resolution purposes.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `get-caller-file` to identify the file path of the function that initiated the call, simulating a common library usage pattern.

// my-library-entry.js
const getCallerFile = require('get-caller-file');

// A function typically exposed by a library
function simulateLibraryCall(position = 2) {
  // We want to find who called 'simulateLibraryCall'.
  // position = 2 gives us the direct caller's file (e.g., index.js).
  // position = 1 would be 'my-library-entry.js' itself.
  return getCallerFile(position);
}

module.exports = simulateLibraryCall;

// --- In a separate file, e.g., index.js ---
// Simulate a user's application file calling into our library
const libraryFunction = require('./my-library-entry.js');

function applicationLogic() {
  const callerFile = libraryFunction();
  console.log(`The file that called 'libraryFunction' is: ${callerFile}`);
  // Expected output (will vary by system path): The file that called 'libraryFunction' is: /full/path/to/this/file/index.js
  return callerFile;
}

applicationLogic();

view raw JSON →