Get the callsite of the caller function
$ npm install caller-callsite
// foo.js
const callerCallsite = require('caller-callsite');
module.exports = () => {
console.log(callerCallsite().getFileName());
//=> '/Users/sindresorhus/dev/unicorn/bar.js'
}
// bar.js
const foo = require('./foo');
foo();
Returns a callsite
object.
Type: object
Type: number
Default: 0
The callsite depth, meaning how many levels we follow back on the stack trace.
For example:
// foo.js
const callerCallsite = require('caller-callsite');
module.exports = () => {
console.log(callerCallsite().getFileName());
//=> '/Users/sindresorhus/dev/unicorn/foobar.js'
console.log(callerCallsite({depth: 1}).getFileName());
//=> '/Users/sindresorhus/dev/unicorn/bar.js'
console.log(callerCallsite({depth: 2}).getFileName());
//=> '/Users/sindresorhus/dev/unicorn/foo.js'
}
// bar.js
const foo = require('./foo');
module.exports = () => {
foo();
}
// foobar.js
const bar = require('./bar');
bar();
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.