Node.js Require Hook

1.0.0 · abandoned · verified Sun Apr 19

node-hook is a low-level utility for intercepting and transforming JavaScript source code before it is loaded by Node.js's CommonJS `require` mechanism. It allows developers to register a synchronous function that receives the raw source and filename, returning a modified source string for immediate evaluation. The current stable version is 1.0.0, released in 2017. Due to its age and reliance on Node.js's CommonJS module loader, it is largely incompatible with modern ES Modules (ESM) environments. Its release cadence was infrequent, with the last update several years ago. Key differentiators include its direct manipulation of `Module._extensions['.js']` for simple, synchronous source transforms, unlike more complex bundlers or build tools, making it suitable for runtime code instrumentation or on-the-fly transpilation in legacy CommonJS applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to register a source code transformation using `node-hook` for `.js` files. It shows how to apply a function that logs the processed filename and modifies the module's export, then unhooks the transform. It also highlights Node.js's module caching behavior.

const { hook, unhook } = require('node-hook');
const path = require('path');
const fs = require('fs');

// Create a dummy file to be required
const dummyFilePath = path.join(__dirname, 'dummy.js');
fs.writeFileSync(dummyFilePath, 'module.exports = { message: "Hello from dummy!" };');

console.log('--- Registering hook ---');

// Register a transform function to log the filename and modify source
function logAndModifySource(source, filename) {
    if (filename === dummyFilePath) {
        console.log(`[HOOK] Processing: ${filename}`);
        return `console.log('Transformed source for ${path.basename(filename)}');\n${source}\nmodule.exports.transformed = true;`;
    }
    return source;
}

hook('.js', logAndModifySource);

console.log('--- Requiring dummy.js ---');
const dummyModule = require('./dummy');

console.log('--- Dummy module content ---');
console.log(dummyModule);

console.log('--- Unhooking .js ---');
unhook('.js'); // Removes the transform

console.log('--- Requiring dummy.js again (should use cached version) ---');
const dummyModuleCached = require('./dummy');
console.log(dummyModuleCached);

// Clean up dummy file
fs.unlinkSync(dummyFilePath);

view raw JSON →