{"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.","language":"javascript","status":"abandoned","last_verified":"Sun Apr 19","install":{"commands":["npm install node-hook"],"cli":null},"imports":["const hook = require('node-hook');","const { hook } = require('node-hook');","const { unhook } = require('node-hook');"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}