首页 > 解决方案 > Get path of file which executed another file

问题描述

I would like to get the path of the file which executed another file.

first.js

const second = require("./second.js");

exports.run = () => {

 second.run();

}

second.js

exports.run = () => {

 let executedPath; // <-- ?

 console.log(`File which executed this function: ${executedPath}`);

}

If you throw an error in the function (throw new Error("test")) the console shows the following:

UnhandledPromiseRejectionWarning: Error: test
    at exports.run (/test/two.js:5:9)
    at exports.run.<anonymous> (/test/one.js:5:8)

So I guess it knows which file executed second.js but how to get the path of it?

标签: javascriptnode.jsnpm

解决方案


You can dig the value out of new Error().stack along these lines:

function executedPath(n) {
    return new Error().
        stack.
        split('\n')[n+1].
        match(/\(([^\)]*):\d+:\d+\)/)[1]
}

推荐阅读