Skip to content

Instantly share code, notes, and snippets.

@wmertens
Created February 8, 2022 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmertens/59a5416206d7371e8fdb42940dbfff73 to your computer and use it in GitHub Desktop.
Save wmertens/59a5416206d7371e8fdb42940dbfff73 to your computer and use it in GitHub Desktop.
spy on NodeJS require stack
// 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