Discover a module's resolved filename
A tool needs to inspect which installed file a package name maps to.
Node.js · Pipe
require.resolve() finds the filename CommonJS require() would load without loading the module. It returns a string or throws MODULE_NOT_FOUND when resolution fails.
require.resolve() uses CommonJS module-resolution rules to find the filename that require() would load, but it does not load or execute that module. You can optionally provide paths that act as starting points for searching module locations; an unresolved request throws MODULE_NOT_FOUND.
require.resolve(request[, options])| Name | Type | Description |
|---|---|---|
request | string | The module path to resolve. |
options | Object | Optional resolution settings. Its paths property supplies starting locations for module lookup. |
options.paths | string[] | Paths from which to start resolving the module location; global folders remain included. |
<string> — the resolved filename; if the module cannot be found, a MODULE_NOT_FOUND error is thrown.
const path = require.resolve('node:path');
console.log(path);Resolves the built-in node:path module to its filename without loading it.
A tool needs to inspect which installed file a package name maps to.
An application supports an optional dependency and must test whether it is installed before loading it.
A resolver must search from a non-default module location.
It returns the filename that CommonJS require() would load, without loading the module itself. The return type is a string, and failure throws MODULE_NOT_FOUND.
Follow-up: How can resolution begin from custom locations? Pass an options object containing paths; each path becomes a starting point for the module-resolution search.
request is the module path to resolve. The optional options object supports paths, an array of strings used as starting locations for resolving the module.
Follow-up: Are those the only locations considered? No; the documented global folders are still included even when custom paths are supplied.
It does not execute the target module; it only computes the filename. If the request cannot be found, the call throws a MODULE_NOT_FOUND error rather than returning a sentinel value.
Follow-up: How would you safely probe an optional dependency? Wrap require.resolve() in try/catch and specifically handle the resolution failure before requiring it.
require()require.resolve.paths()MODULE_NOT_FOUNDCommonJS modules