node/test/fixtures/module-hooks/add-hook.js
Joyee Cheung e85964610c module: implement module.registerHooks()
PR-URL: https://github.com/nodejs/node/pull/55698
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
2024-12-09 23:27:08 +00:00

30 lines
824 B
JavaScript

'use strict';
const { fileURLToPath } = require('url');
const { registerHooks } = require('module');
// This is a simplified version of the pirates package API to
// check that a similar API can be built on top of the public
// hooks.
function addHook(hook, options) {
function load(url, context, nextLoad) {
const result = nextLoad(url, context);
const index = url.lastIndexOf('.');
const ext = url.slice(index);
if (!options.exts.includes(ext)) {
return result;
}
const filename = fileURLToPath(url);
if (!options.matcher(filename)) {
return result;
}
return { ...result, source: hook(result.source.toString(), filename) }
}
const registered = registerHooks({ load });
return function revert() {
registered.deregister();
};
}
module.exports = { addHook };