Skip to content

Instantly share code, notes, and snippets.

@mohd-akram
Created June 10, 2024 11:48
Show Gist options
  • Save mohd-akram/75a668f54df56790fb2a2216f695277c to your computer and use it in GitHub Desktop.
Save mohd-akram/75a668f54df56790fb2a2216f695277c to your computer and use it in GitHub Desktop.
A custom Node.js console that writes to stderr and the debug console
const inspector = require("inspector");
// See:
// https://github.com/nodejs/node/blob/v22.2.0/lib/internal/util/inspector.js#L83
// Wrap a console implemented by Node.js with features from the VM inspector
function wrapConsole(console) {
const inspectorConsole = inspector.console;
for (const key of Object.keys(inspectorConsole)) {
// If the console has the same method as the inspector console,
// then wrap these two methods into one.
if (console.hasOwnProperty(key)) {
const func = console[key];
console[key] = function () {
func.apply(console, arguments);
inspectorConsole[key].apply(inspectorConsole, arguments);
}.bind(console);
Object.defineProperty(console[key], "name", {
value: key,
});
} else {
// Add additional console APIs from the inspector
console[key] = inspectorConsole[key];
}
}
return console;
}
module.exports = wrapConsole(new console.Console(process.stderr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment