elastic/require-in-the-middle

Intercept absolute paths

Closed this issue · 4 comments

It seems like it is impossible to use require-in-the-middle to intercept requires of absolute file paths. For instance, I would like to intercept the require of /var/runtime/util.js which is outside of my node_modules and not a core module. I tried to do hook(['/var/runtime/util'], onRequire), but when require('/var/runtime/util') is called, require-in-the-middle logs require-in-the-middle could not parse filename: /var/runtime/util.js +0ms.

It looks like require-in-the-middle is using the module-details-from-path module, which fails to parse this absolute path.

This module is meant as a way to patch files in 3rd party modules that you can't normally edit yourself. If the file you're trying to patch is not inside node_modules, I would assume that you could just go and edit the file manually. What's the use-case for wanting to patch a file outside of the node_modules folder? I'd be happy to consider this if it makes sense 😃

I am trying to patch the runtime internals of AWS lambda. Specifically, the /var/runtime/RAPIDClient.js file.

I am happy to provide a PR if you'd like. I already modified a version locally which works with the restriction that the only way to intercept files like this is by specifying their absolute path in the whitelist.

const Hook = require("require-in-the-middle");

// also works with "/var/runtime/RAPIDClient.js"
Hook(["/var/runtime/RAPIDClient"], (exports, name, basedir) => {
  console.log(name) // RAPIDClient
  console.log(basedir) // /var/runtime

  return exports;
});

Yes, please send a PR. It would be great to support this use-case