node:module
- это встроенный модуль Node.js, который предоставляет API для взаимодействия с системой модулей Node.js. Это "модуль о модулях", дающий низкоуровневый доступ к:
const Module = require('node:module');
// Получаем объект Module
console.log(Module);
const customModule = new Module('custom-module', null);
customModule._compile('console.log("Hello from custom module!")', 'custom.js');
Доступ к кэшу загруженных модулей:
const cache = Module._cache;
console.log(Object.keys(cache)); // Список загруженных модулей
Разрешение полного пути к модулю:
const path = Module._resolveFilename('./my-module', null, true);
console.log(path); // Полный абсолютный путь
Создание функции require с контекстом:
const { createRequire } = require('node:module');
const myRequire = createRequire('/path/to/context');
const pkg = myRequire('./package.json');
function hotReload(modulePath) {
const fullPath = require.resolve(modulePath);
delete Module._cache[fullPath];
return require(fullPath);
}
const req = Module.createRequire(import.meta.url);
const localModule = req('./local-module');
const originalRequire = Module.prototype.require;
Module.prototype.require = function(id) {
console.log(`Requiring: ${id}`);
return originalRequire.call(this, id);
};
Начиная с Node.js v16.0.0, можно использовать префикс node:
для явного указания встроенных модулей:
// Эквивалентны, но node: явно указывает на встроенный модуль
const mod1 = require('module');
const mod2 = require('node:module');
class CustomLoader extends Module {
_compile(content, filename) {
// Кастомная логика компиляции
super._compile(content.replace(/console.log/g, ''), filename);
}
}
const module = require('node:module');
module.syncBuiltinESMExports();
_
(подчеркивание), что означает их нестабильность node:module
- это мощный инструмент для продвинутой работы с системой модулей Node.js. Он предоставляет низкоуровневый API для управления загрузкой модулей, создания изолированных контекстов и реализации кастомной логики разрешения зависимостей. Хотя большинству приложений не требуется прямое взаимодействие с этим модулем, он незаменим при создании инструментов разработки, систем горячей перезагрузки и продвинутых загрузчиков модулей.