Skip to content

Commit

Permalink
lib: requireStack property for MODULE_NOT_FOUND
Browse files Browse the repository at this point in the history
Include the stack of requires that led to a MODULE_NOT_FOUND error.

PR-URL: #25690
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
ofrobots committed Feb 15, 2019
1 parent 128170f commit 05cd1a0
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
7 changes: 6 additions & 1 deletion doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -1964,7 +1964,12 @@ an `Error` with this code will be emitted.

<a id="MODULE_NOT_FOUND"></a>
### MODULE_NOT_FOUND

<!-- YAML
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/25690
description: Added `requireStack` property.
-->
A module file could not be resolved while attempting a [`require()`][] or
`import` operation.

Expand Down
7 changes: 7 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -606,9 +606,16 @@ Module._resolveFilename = function(request, parent, isMain, options) {
// Look up the filename first, since that's the cache key.
var filename = Module._findPath(request, paths, isMain);
if (!filename) {
const requireStack = [];
for (var cursor = parent;
cursor;
cursor = cursor.parent) {
requireStack.push(cursor.filename || cursor.id);
}
// eslint-disable-next-line no-restricted-syntax
var err = new Error(`Cannot find module '${request}'`);
err.code = 'MODULE_NOT_FOUND';
err.requireStack = requireStack;
throw err;
}
return filename;
Expand Down
5 changes: 4 additions & 1 deletion lib/internal/modules/esm/default_resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,11 @@ function resolve(specifier, parentURL) {
parentURL || pathToFileURL(`${process.cwd()}/`).href);
} catch (e) {
if (typeof e.message === 'string' &&
StringStartsWith(e.message, 'Cannot find module'))
StringStartsWith(e.message, 'Cannot find module')) {
e.code = 'MODULE_NOT_FOUND';
// TODO: also add e.requireStack to match behavior with CJS
// MODULE_NOT_FOUND.
}
throw e;
}

Expand Down

0 comments on commit 05cd1a0

Please sign in to comment.