Nodejs: get filename of caller function

前端 未结 7 1232
心在旅途
心在旅途 2020-11-30 03:41

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 functi

7条回答
  •  鱼传尺愫
    2020-11-30 04:01

    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;
    }
    

提交回复
热议问题