Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Error: Cannot find module 'test' #391

@sjinks

Description

@sjinks

Environment

$ node -v
v22.17.0

[email protected]

Reproduction

test.mts:

import { test } from 'node:test';

test('noop', {});

Run with:

node --import jiti/register --test test.mts

Output:

node:internal/modules/cjs/loader:1401
  const err = new Error(message);
              ^

Error: Cannot find module 'test'
Require stack:
- <redacted>/test.mts
    at Function._resolveFilename (node:internal/modules/cjs/loader:1401:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at jitiResolve (<redacted>/node_modules/jiti/dist/jiti.cjs:1:190064)
    at jitiRequire (<redacted>/node_modules/jiti/dist/jiti.cjs:1:192130)
    at import (<redacted>/node_modules/jiti/dist/jiti.cjs:1:202951)
    at _module (file://<redacted>/test.mts:1:259)
    at file://<redacted>/test.mts:10:7
    at ModuleJob.run (node:internal/modules/esm/module_job:329:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:644:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '<redacted>/test.mts' ]
}

Describe the bug

When a script tries to import the node:test module, it crashes with the "Cannot find module 'test'" error.

I will try to submit a fix, but since I am not familiar with the codebase, it might take some time.

Additional context

According to the official documentation,

Currently the built-in modules that requires the node: prefix are:

node:sea
node:sqlite
node:test
node:test/reporters

The list of these modules is exposed in module.builtinModules, including the prefix.

However, according to the history, prefix-only modules are included only since v23.5.0.

As far as I understand, the bug lives here:

jiti/src/require.ts

Lines 34 to 36 in 61fa803

if (builtinModules.includes(id) || id === ".pnp.js" /* #24 */) {
return nativeImportOrRequire(ctx, id, opts.async);
}

The possible fix is to use module.isBuiltin():

$ node
Welcome to Node.js v22.17.0.
Type ".help" for more information.
> const m = require('node:module');
undefined
> m.isBuiltin('node:test')
true
> m.isBuiltin('node:fs')
true
> m.isBuiltin('fs')
true
> m.isBuiltin('test') // should be false, as `test` is a prefix-only module
false

Logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions