Get the path of the parent module that called the current module
npx @tessl/cli install tessl/npm-parent-module@3.1.0Parent Module provides a simple utility to get the path of the parent module that called the current module. It leverages the callsites library to analyze the JavaScript call stack and identify the calling module's location, making it useful for debugging, logging, and dynamic module resolution.
npm install parent-moduleimport parentModule from 'parent-module';// bar.js
import parentModule from 'parent-module';
export default function bar() {
console.log(parentModule());
//=> '/Users/sindresorhus/dev/unicorn/foo.js'
}
// foo.js
import bar from './bar.js';
bar();Gets the path of the parent module that called the current module, with support for both immediate parent detection and multi-level resolution.
/**
* Get the path of the parent module
* @param filePath - The file path of the module of which to get the parent path
* @returns The file path of the parent module, or undefined if no parent can be determined
*/
function parentModule(filePath?: string): string | undefined;Parameters:
filePath (optional): string - The file path of the module of which to get the parent path. When provided, returns the parent of the module that called the specified file path. When omitted, returns the immediate parent module.Returns:
string | undefined - The file path of the parent module, or undefined if no parent can be determinedBehavior:
filePath: Returns the path of the immediate parent module (2nd level up in call stack)filePath: Traverses the call stack to find the parent of the module that called the specified file pathUsage Examples:
// Example 1: Basic usage (immediate parent)
// In module-b.js
import parentModule from 'parent-module';
export function logCaller() {
console.log(parentModule());
// When called from module-a.js, outputs: '/path/to/module-a.js'
}
// Example 2: Multi-level parent resolution
// In deeply-nested.js
import parentModule from 'parent-module';
export function findSpecificParent() {
// Find the parent of the module that called 'intermediate.js'
const parent = parentModule('/path/to/intermediate.js');
console.log(parent);
// Outputs the path of the module that called intermediate.js
}
// Example 3: Integration with package.json reading
import path from 'node:path';
import {readPackageUpSync} from 'read-pkg-up';
import parentModule from 'parent-module';
// Get package.json of the calling module
const parentPkg = readPackageUpSync({
cwd: path.dirname(parentModule())
}).pkg;
console.log(parentPkg.name); // Name of the calling module's packageFull TypeScript definitions are included via index.d.ts, providing complete type safety and IntelliSense support.
import parentModule from 'parent-module';
// TypeScript knows the return type is string | undefined
const parent: string | undefined = parentModule();
const specificParent: string | undefined = parentModule('/path/to/file.js');