Module Path
Retrieving Modules
Programming Guide
Module Management
Code Implementation

How to retrieve a module's path?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Retrieving a module path is really about asking the runtime where a module came from. The exact API depends on the language and module system, and the right answer changes when the module is built in, packaged, or resolved through a virtual loader instead of a normal file on disk.

Python: start with __file__ and importlib

For ordinary imported Python modules, the first place to look is module.__file__. It points at the file that Python loaded, which is often enough if you want the module directory or need to load data stored next to the module.

python
1from pathlib import Path
2import json
3
4module_file = Path(json.__file__).resolve()
5module_dir = module_file.parent
6
7print("module file:", module_file)
8print("module dir:", module_dir)

That works well for modules that live on disk. If you want a more explicit lookup step, importlib.util.find_spec() gives you the import metadata without forcing you to inspect the module object manually.

python
1from importlib.util import find_spec
2
3spec = find_spec("json")
4print("origin:", spec.origin)
5print("search locations:", spec.submodule_search_locations)

spec.origin is often more reliable than guessing at package layout yourself. For a package, spec.submodule_search_locations tells you where Python will search for submodules, which is useful when the package spans multiple directories.

Loading resources relative to a Python module

The common follow-up is not "what is the path" but "how do I find files next to the module." Use pathlib and anchor the resource path to the module location rather than to the current working directory.

python
1from pathlib import Path
2import my_package
3
4base_dir = Path(my_package.__file__).resolve().parent
5config_path = base_dir / "data" / "settings.json"
6
7print(config_path)

That approach is robust when the process is launched from different directories. If you use the process working directory instead, the same code can pass locally and fail in production.

For modern package data, importlib.resources is often better than raw paths because it can also work with some packaged layouts.

python
1from importlib import resources
2
3config_text = resources.files("my_package").joinpath("data/settings.json").read_text()
4print(config_text)

Use raw paths only when a true filesystem path is required by another API.

Node.js: distinguish current module from resolved dependency

In Node.js, the question splits into two different cases. You may need the location of the current file, or you may need the location of a dependency as resolved by Node's module loader.

In CommonJS, __dirname gives the current file's directory, while require.resolve() tells you what file Node would load for a given module request.

javascript
1const path = require("path");
2
3console.log("current dir:", __dirname);
4console.log("express entry:", require.resolve("express"));
5console.log("relative module:", require.resolve("./lib/helper"));
6console.log("joined resource:", path.join(__dirname, "data", "config.json"));

In ES modules, __dirname is not available. Start from import.meta.url and convert the file URL to a filesystem path.

javascript
1import path from "node:path";
2import { fileURLToPath } from "node:url";
3
4const currentFile = fileURLToPath(import.meta.url);
5const currentDir = path.dirname(currentFile);
6
7console.log(currentFile);
8console.log(currentDir);

If you need dependency resolution in ESM, you can create a resolver that behaves like CommonJS.

javascript
1import { createRequire } from "node:module";
2
3const require = createRequire(import.meta.url);
4console.log(require.resolve("express"));

Cases where there is no useful disk path

Not every module maps cleanly to a file on disk. Built-in Python modules may have no meaningful __file__. Namespace packages can span several locations. In Node.js, core modules such as fs are built into the runtime, so there may not be a normal file path to return.

That means your code should treat path discovery as best-effort metadata, not as a universal guarantee. If your real goal is loading package data, use the package's resource API when one exists. If your goal is logging or diagnostics, be prepared for values such as None, a virtual origin, or a non-filesystem specifier.

Choosing the right API for the job

Use module.__file__ in Python when you already have the imported module object. Use find_spec() when you want import-system metadata. Use __dirname or import.meta.url when you need the current Node module's location. Use require.resolve() or createRequire(...).resolve() when you need the resolved entry point of another module.

Those tools answer related questions, but they are not interchangeable. The main failure mode is using one API to solve a different path problem.

Common Pitfalls

A common mistake is confusing the module path with the current working directory. They are independent, and code that depends on the working directory is fragile.

Another mistake is assuming every module has a real file on disk. Built-in modules, namespace packages, bundled applications, and custom loaders can break that assumption.

A third mistake is using raw file paths when the runtime already offers a resource-loading API. In Python, importlib.resources is often safer than joining strings onto __file__.

Summary

  • In Python, start with module.__file__ for normal modules and importlib.util.find_spec() for import metadata.
  • Use pathlib to build paths relative to a module instead of relative to the working directory.
  • In CommonJS, use __dirname for the current file and require.resolve() for dependency resolution.
  • In ES modules, use import.meta.url and convert it with fileURLToPath.
  • Treat module paths as runtime metadata, not as a guarantee that every module is backed by a normal file.

Course illustration
Course illustration

All Rights Reserved.