Nodejs: get filename of caller function

I wonder how-to get an absolute path of a caller of a function?

Let say that:

in file a.js I call b(); b() is a function defined in file b.js. a.jsrequires b . So how do I get a.js absolute path from b.js in node?

This is an example how to use stacktrace to find caller file in node

function _getCallerFile() {
    try {
        var err = new Error();
        var callerfile;
        var currentfile;

        Error.prepareStackTrace = function (err, stack) { return stack; };

        currentfile = err.stack.shift().getFileName();

        while (err.stack.length) {
            callerfile = err.stack.shift().getFileName();

            if(currentfile !== callerfile) return callerfile;
        }
    } catch (err) {}
    return undefined;
}

You can use require.resolve(module) to determine the full path of a module:

var path = require.resolve("a");

//or

var path = require.resolve("./a.js");

Not exactly answering the question here but some might appreciate this information.

With NodeJS & Forever(-monitor), the following contains a filename from which the process was started:

process.mainModule.filename

Haven't tried many uses™ though.

This seems to be a pretty decent explanation: https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi.

Getting a stacktrace in JavaScript is quite hard. The best method I've found is to throw an Error, catch it, get the stack from Error.getStack() (not implemented in all browsers, that means you IE.) and formatting the output.

Each stack frame gives you a filepath, line number and function name. Webkit even has support for arguments but that wasn't working yet when I last checked.

Then there is the problem of tracing code across different events.

I actually wrote a blog post about this: http://fritsvancampen.wordpress.com/2013/03/28/error-handling-in-javascript-a-better-way/

Failing to restore the prepareStackTrace function can cause issues. Here's an example that removes side-effects

function _getCallerFile() {
    var originalFunc = Error.prepareStackTrace;

    var callerfile;
    try {
        var err = new Error();
        var currentfile;

        Error.prepareStackTrace = function (err, stack) { return stack; };

        currentfile = err.stack.shift().getFileName();

        while (err.stack.length) {
            callerfile = err.stack.shift().getFileName();

            if(currentfile !== callerfile) break;
        }
    } catch (e) {}

    Error.prepareStackTrace = originalFunc; 

    return callerfile;
}