{"id":11427,"library":"node-hook","title":"Node.js Require Hook","description":"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.","status":"abandoned","version":"1.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/bahmutov/node-hook","tags":["javascript","require","node","load","hook","transform"],"install":[{"cmd":"npm install node-hook","lang":"bash","label":"npm"},{"cmd":"yarn add node-hook","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-hook","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"node-hook is a CommonJS module and must be imported using `require()`. It does not support ES module `import` syntax.","wrong":"import hook from 'node-hook';","symbol":"hook","correct":"const hook = require('node-hook');"},{"note":"The `hook` method is a property of the default export. Destructuring or direct property access is the correct usage. Calling it as a function without arguments will fail.","wrong":"const hook = require('node-hook').hook();","symbol":"hook.hook","correct":"const { hook } = require('node-hook');"},{"note":"Used to remove a previously registered transform function for a given file extension.","symbol":"hook.unhook","correct":"const { unhook } = require('node-hook');"}],"quickstart":{"code":"const { hook, unhook } = require('node-hook');\nconst path = require('path');\nconst fs = require('fs');\n\n// Create a dummy file to be required\nconst dummyFilePath = path.join(__dirname, 'dummy.js');\nfs.writeFileSync(dummyFilePath, 'module.exports = { message: \"Hello from dummy!\" };');\n\nconsole.log('--- Registering hook ---');\n\n// Register a transform function to log the filename and modify source\nfunction logAndModifySource(source, filename) {\n    if (filename === dummyFilePath) {\n        console.log(`[HOOK] Processing: ${filename}`);\n        return `console.log('Transformed source for ${path.basename(filename)}');\\n${source}\\nmodule.exports.transformed = true;`;\n    }\n    return source;\n}\n\nhook('.js', logAndModifySource);\n\nconsole.log('--- Requiring dummy.js ---');\nconst dummyModule = require('./dummy');\n\nconsole.log('--- Dummy module content ---');\nconsole.log(dummyModule);\n\nconsole.log('--- Unhooking .js ---');\nunhook('.js'); // Removes the transform\n\nconsole.log('--- Requiring dummy.js again (should use cached version) ---');\nconst dummyModuleCached = require('./dummy');\nconsole.log(dummyModuleCached);\n\n// Clean up dummy file\nfs.unlinkSync(dummyFilePath);\n","lang":"javascript","description":"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."},"warnings":[{"fix":"Review the commit history and issue tracker for '#11' if migrating from very old versions. For new projects, treat 1.0.0 as the baseline.","message":"Version 1.0.0 introduced breaking changes; however, the specific details beyond 'release 1.0.0 closes #11' are not documented. Users upgrading from pre-1.0.0 versions should review their usage patterns carefully. Given the project's age, this is primarily a historical note.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"To force a module to reload and re-apply transforms, you must delete its entry from `require.cache` before calling `require()` again, e.g., `delete require.cache[require.resolve('./your-module')]`.","message":"Node.js caches compiled modules. If you apply a hook and then `require` the same file again, the cached version will be returned, and your transform function will not be re-applied. This can lead to unexpected behavior where changes aren't reflected.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Use alternative tools like custom loaders (`--experimental-loader`) for Node.js ESM transformation, or transpile your code to CommonJS before runtime if `node-hook` is essential for a specific part of your application.","message":"node-hook operates exclusively on Node.js's CommonJS `require` mechanism. It is fundamentally incompatible with ES Modules (ESM) `import` statements and module loading processes. Attempting to use it in an ESM project or to hook ESM files will not work as intended.","severity":"breaking","affected_versions":">=0.1.0"},{"fix":"Evaluate whether an active, maintained alternative can fulfill the required functionality. If `node-hook` is critical, consider forking and maintaining it yourself, or thoroughly vetting it for compatibility and security in your specific environment.","message":"The project appears to be abandoned, with its last release in 2017. This means it receives no updates, bug fixes, or security patches. It may not work with newer Node.js versions or dependencies, and could pose a security risk due to unaddressed vulnerabilities.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use the CommonJS `require` syntax: `const hook = require('node-hook');`","cause":"Attempting to use `import hook from 'node-hook';` in a CommonJS context or a file without `'type': 'module'` in `package.json`.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Access the `hook` function as a property: `const { hook } = require('node-hook');` or `const nodeHook = require('node-hook'); nodeHook.hook(...);`","cause":"Incorrectly trying to call `require('node-hook').hook()` as a function, or attempting to access `hook` before it's properly assigned from the module's export.","error":"TypeError: Cannot read properties of undefined (reading 'hook') at Object.<anonymous> (test.js:3:16)"},{"fix":"To ensure your transform is applied, clear the module from the `require.cache` before re-requiring: `delete require.cache[require.resolve('./your-module')];`","cause":"Node.js caches modules after their initial `require()` call. Subsequent `require()` calls for the same file return the cached version without re-running transforms.","error":"My transform function isn't being applied to subsequent `require()` calls for the same file."}],"ecosystem":"npm"}