Module sync hook 在静态分析中的隐秘应用
利用 module.syncBuiltinESMExports 和内置模块的同步钩子,在运行时注入新 API 而不修改源代码。 · 难度:入门 · +10XP
Module sync hook 在静态分析中的隐秘应用
Node.js 的 module 对象提供 syncBuiltinESMExports 方法,允许强制同步内置模块的 ESM 导出,这常用于热修复或 mock。更深入的是,配合 require.extensions 或 loader hook,可以在模块编译阶段分析 AST 并注入依赖。本教程演示如何创建一个预处理器,在模块加载时自动添加性能计时代码。
const Module = require('module');
const originalRequire = Module.prototype.require;
Module.prototype.require = function(id) {
const exports = originalRequire.apply(this, arguments);
if (id === 'fs') {
// 在fs上添加自定义方法
exports.readFileSyncAsync = (path) => {
return new Promise((resolve) => {
setImmediate(() => resolve(exports.readFileSync(path)));
});
};
}
return exports;
};
// 同步内置ESM导出
module.syncBuiltinESMExports();