lib: requireStack property for MODULE_NOT_FOUND

Include the stack of requires that led to a MODULE_NOT_FOUND error.

PR-URL: https://github.com/nodejs/node/pull/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>
This commit is contained in:
Ali Ijaz Sheikh 2019-01-28 11:24:37 -08:00
parent 128170f5c6
commit 05cd1a0929
3 changed files with 17 additions and 2 deletions

View File

@ -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.

View File

@ -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;

View File

@ -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;
}