Safe Monkeypatching for JavaScript

1.2.1 · maintenance · verified Sun Apr 19

The `shimmer` package (version 1.2.1) is a JavaScript utility designed for safe monkeypatching of functions, primarily within Node.js CommonJS environments. It provides a set of tools, including `wrap`, `massWrap`, `unwrap`, and `massUnwrap`, to intercept and augment the behavior of existing functions on objects or entire modules. The library's core philosophy is to add behavior around an original function, rather than replacing it, and includes important guidelines for maintaining function integrity (e.g., preserving return values, not altering async/sync nature). Released approximately seven years ago, its current status suggests it is in maintenance mode rather than active development. It differentiates itself by providing explicit safety mechanisms and logging for potential issues during monkeypatching, defaulting to `console.error` for non-throwing error reporting. This makes it suitable for extending or observing existing Node.js module functionality with reduced risk compared to direct function reassignment.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `shimmer.wrap` to intercept and log details of `http.request` calls in Node.js, and then `shimmer.unwrap` to restore the original function.

const http = require('http');
const shimmer = require('shimmer');

console.log('Original http.request is:', http.request.__wrapped ? 'wrapped' : 'not wrapped');

shimmer.wrap(http, 'request', function (original) {
  return function () {
    console.log('>>> Intercepting http.request: Starting request!');
    const args = Array.from(arguments);
    const options = typeof args[0] === 'string' ? new URL(args[0]) : args[0];
    console.log('    Request options:', options);
    const returned = original.apply(this, arguments);
    console.log('<<< Intercepting http.request: Done setting up request.');
    return returned;
  };
});

console.log('Patched http.request is:', http.request.__wrapped ? 'wrapped' : 'not wrapped');

// Example usage to trigger the wrapped function
const req = http.request('http://www.google.com', (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    // console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

req.end();

// Clean up
shimmer.unwrap(http, 'request');
console.log('Unwrapped http.request is:', http.request.__wrapped ? 'wrapped' : 'not wrapped');

view raw JSON →