Created
June 10, 2024 11:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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