Skip to content

Patch/Instrument a module #49452

Closed
Closed
@Flarna

Description

@Flarna

Maybe the information I'm looking for is already somewhere but I'm not able to find it. I'm happy if I get redirected.
I'm also quite new in the ECMAModules area so I may simply don't know significant details so please excuse if my question is inaccurate or improper.

There are quite some tools (Transformers, APMs,....) out which monkey patch module._load() and/or module.prototype.require() to hook into loading of CJS module loading to modify their content. For APMs the modification is usually just to wrap a handful of the exported functions but keep the rest as it is.

I tried to find the corresponding solution for ECMAModuls but I failed. I found nodejs/modules#98 which also describes this requirement and it links to https://github.com/bmeck/node-apm-loader-example but this sample seems to no longer work (useing 12.4.0). I get following error (after fixing a few nits):

const exports = Object.create(fs, {
                              ^

ReferenceError: Cannot access 'fs' before initialization
    at file:///C:/workspaces/GitHubForks/node-apm-loader-example/overloads/fs.mjs:4:31
    at ModuleJob.run (internal/modules/esm/module_job.js:111:37)
    at async Loader.import (internal/modules/esm/loader.js:128:24)

Even if it would work I have the impression that this solution actually changes the URL in module map for a patched module, e.g. fs would be then URL to ./fs.mjs. For an user importing fs this is don't care but if there are more hooks listening on fs only the first one would be applied. At least in CJS I have seen several times that more then one APM/Transformer is in use within one application.

Besides that this sample is in my opinion unneeded complicated for the common usecase to just wrap a few exported functions but keep the remaining stuff as it is. Would it be possible to create a simpler hook for this?

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