Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: improve error message on missing module #25690

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
13 changes: 12 additions & 1 deletion lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -606,9 +606,20 @@ 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);
}
let message = `Cannot find module '${request}'`;
if (requireStack.length > 0) {
message = message + '\nRequire stack:\n- ' + requireStack.join('\n- ');
}
// eslint-disable-next-line no-restricted-syntax
var err = new Error(`Cannot find module '${request}'`);
var err = new Error(message);
err.code = 'MODULE_NOT_FOUND';
err.requireStack = requireStack;
ofrobots marked this conversation as resolved.
Show resolved Hide resolved
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
6 changes: 3 additions & 3 deletions test/fixtures/require-resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,21 @@ assert.strictEqual(
// Verify that existing paths are removed.
assert.throws(() => {
require.resolve('bar', { paths: [] })
}, /^Error: Cannot find module 'bar'$/);
}, /^Error: Cannot find module 'bar'/);

// Verify that resolution path can be overwritten.
{
// three.js cannot be loaded from this file by default.
assert.throws(() => {
require.resolve('three')
}, /^Error: Cannot find module 'three'$/);
}, /^Error: Cannot find module 'three'/);

// If the nested-index directory is provided as a resolve path, 'three'
// cannot be found because nested-index is used as a starting point and not
// a searched directory.
assert.throws(() => {
require.resolve('three', { paths: [nestedIndex] })
}, /^Error: Cannot find module 'three'$/);
}, /^Error: Cannot find module 'three'/);

// Resolution from nested index directory also checks node_modules.
assert.strictEqual(
Expand Down
2 changes: 1 addition & 1 deletion test/parallel/test-internal-modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const assert = require('assert');

assert.throws(function() {
require('internal/freelist');
}, /^Error: Cannot find module 'internal\/freelist'$/);
}, /^Error: Cannot find module 'internal\/freelist'/);

assert.strictEqual(
require(fixtures.path('internal-modules')),
Expand Down
4 changes: 2 additions & 2 deletions test/parallel/test-loaders-hidden-from-users.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ common.expectsError(
require('internal/bootstrap/loaders');
}, {
code: 'MODULE_NOT_FOUND',
message: 'Cannot find module \'internal/bootstrap/loaders\''
message: /Cannot find module 'internal\/bootstrap\/loaders'/
}
);

Expand All @@ -20,6 +20,6 @@ common.expectsError(
require('owo');
}, {
code: 'MODULE_NOT_FOUND',
message: 'Cannot find module \'owo\''
message: /Cannot find module 'owo'/
}
);
7 changes: 4 additions & 3 deletions test/parallel/test-module-loading-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,10 @@ common.expectsError(
message: 'The argument \'id\' must be a non-empty string. Received \'\''
});

common.expectsError(
assert.throws(
() => { require('../fixtures/packages/is-dir'); },
{
code: 'MODULE_NOT_FOUND',
message: 'Cannot find module \'../fixtures/packages/is-dir\''
});
message: /Cannot find module '\.\.\/fixtures\/packages\/is-dir'/
}
);
6 changes: 3 additions & 3 deletions test/parallel/test-module-multi-extensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fs.writeFileSync(dotfileWithExtension, 'console.log(__filename);', 'utf8');
require(modulePath);
assert.throws(
() => require(`${modulePath}.foo`),
new Error(`Cannot find module '${modulePath}.foo'`)
(err) => err.message.startsWith(`Cannot find module '${modulePath}.foo'`)
);
require(`${modulePath}.foo.bar`);
delete require.cache[file];
Expand All @@ -47,7 +47,7 @@ fs.writeFileSync(dotfileWithExtension, 'console.log(__filename);', 'utf8');
const modulePath = path.join(tmpdir.path, 'test-extensions');
assert.throws(
() => require(modulePath),
new Error(`Cannot find module '${modulePath}'`)
(err) => err.message.startsWith(`Cannot find module '${modulePath}'`)
);
delete require.cache[file];
Module._pathCache = Object.create(null);
Expand All @@ -69,7 +69,7 @@ fs.writeFileSync(dotfileWithExtension, 'console.log(__filename);', 'utf8');
const modulePath = path.join(tmpdir.path, 'test-extensions.foo');
assert.throws(
() => require(modulePath),
new Error(`Cannot find module '${modulePath}'`)
(err) => err.message.startsWith(`Cannot find module '${modulePath}'`)
);
delete require.extensions['.foo.bar'];
Module._pathCache = Object.create(null);
Expand Down
2 changes: 2 additions & 0 deletions test/parallel/test-repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,8 @@ const errorTests = [
expect: [
'Thrown:',
/^{ Error: Cannot find module 'internal\/repl'/,
/^Require stack:/,
/^- <repl>/,
/^ at .*/,
/^ at .*/,
/^ at .*/,
Expand Down
15 changes: 8 additions & 7 deletions test/sequential/test-module-loading.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ require('../fixtures/node_modules/foo');
assert.ok(my_path.path_func instanceof Function);
// this one does not exist and should throw
assert.throws(function() { require('./utils'); },
/^Error: Cannot find module '\.\/utils'$/);
/^Error: Cannot find module '\.\/utils'/);
}

let errorThrown = false;
Expand Down Expand Up @@ -170,12 +170,13 @@ assert.strictEqual(require('../fixtures/registerExt2').custom, 'passed');
assert.strictEqual(require('../fixtures/foo').foo, 'ok');

// Should not attempt to load a directory
try {
tmpdir.refresh();
require(tmpdir.path);
} catch (err) {
assert.strictEqual(err.message, `Cannot find module '${tmpdir.path}'`);
}
assert.throws(
() => {
tmpdir.refresh();
require(tmpdir.path);
},
(err) => err.message.startsWith(`Cannot find module '${tmpdir.path}`)
);

{
// Check load order is as expected
Expand Down