0

Get function caller file with line number

Function JavaScript 1 revisions 397 a year ago a year ago
const stackTrace = require('stack-trace');

function getCaller() {
	const trace = stackTrace.get();
	return `${trace[2].getFileName()}:${trace[2].getLineNumber()}`;
}

This function uses stack-trace module to extract the caller.

The function gets absolute paths by default, see below for relatives paths.

Usage

While the usage is pretty simple...

function otherFunc() {
    console.log(getCaller());
}

There's a catch: you should be copying the code above as is because if you, for example, copy the content of the function directly that would not work and you'd need to modify the trace index.

Relative paths

Here's a modified version of this function:

const stackTrace = require('stack-trace');
const path = require('path');

function getCaller() {
    const trace = stackTrace.get();
    const root = path.dirname(__dirname);
    return `.${trace[2].getFileName().substring(root.length)}:${trace[2].getLineNumber()}`;
}

I haven't tested that myself but I guess you need this function to be put in a file in root folder of your project to work, I guess.