Skip to content

Regression in "require" in ES6 modules. Fails to find "ws" module. #23503

@RamiHg

Description

@RamiHg

It looks like a recent change to revert a commit that removed uses of require didn't quite fully revert to the old behavior.

I was getting a bizarre error where Node would refuse to find the "ws" module even though I had installed it using npm install ws. I build my code using -sMODULARIZE -sEXPORT_ES6. The error was:

Error: Cannot find module 'ws'
Require stack:
- /noop.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1060:15)
    at Module._load (node:internal/modules/cjs/loader:905:27)
    at Module.require (node:internal/modules/cjs/loader:1127:19)
    at require (node:internal/modules/helpers:112:18)

"ws" was getting imported from libsockfs.js in the listen function:

        var WebSocketServer = require('ws').Server;
        var host = sock.saddr;

The original code that was initially reverted called createRequire like this:

  const { createRequire } = await import('module');
  let dirname = import.meta.url;
  if (dirname.startsWith("data:")) {
    dirname = '/';
  }
  /** @suppress{duplicate} */
  var require = createRequire(dirname);

However, the change that re-introduced the old code instead introduced it as:

  const { createRequire } = await import('module');
  /** @suppress{duplicate} */
  var require = createRequire('/');

I'm not very familiar with Javascript and Node, but after much head-scratching, I tracked it down to that piece of code. If I replace the createRequire with the original version (the one that first checks for "data:"), my code works!

I can create a simple PR to do that fix if needed.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions