Created
February 8, 2022 22:36
-
-
Save wmertens/59a5416206d7371e8fdb42940dbfff73 to your computer and use it in GitHub Desktop.
spy on NodeJS require stack
This file contains 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
// Require this in your program, or load it with node's -r flag | |
const Mod = require('module') | |
const req = Mod.prototype.require | |
let indent = '' | |
const rootRE = new RegExp(process.cwd(), 'g') | |
const stack = [] | |
Mod.prototype.require = function() { | |
try { | |
const request = arguments[0] | |
const file = (new Error().stack.split('\n')[3] || '').trim() | |
const loc = file | |
.replace(/^at /, '> ') | |
.replace(new RegExp(process.cwd(), 'g'), '.') | |
const line = (indent + loc + ': ' + request).replace(rootRE, '.') | |
stack.push(line) | |
console.error(line) | |
indent += '| ' | |
const result = req.apply(this, arguments) | |
indent = indent.slice(0, -2) | |
stack.pop() | |
return result | |
} catch (err) { | |
console.error( | |
'!!! require:', | |
require('util').inspect(arguments), | |
err.message | |
) | |
stack.forEach(line => console.error('!!! require:', line)) | |
throw err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment