Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
From a function, how to get details about the module which actually called this function?

In a general-purpose function, I would like to get informations about the module which calls this function (especially the base directory, which can itself be retrieved inside a module with path.dirname(module.filename)).

What I tried

For now, the only way I found to do it is to add module as a parameter for the function:

lib/my-lib.js:

const path = require('path');

exports.print_calling_module_path = function(calling_module) {
    console.log(path.dirname(calling_module.filename));
}

main.js:

const my_lib = require('./lib/my-lib.js');

console.log('Here is the path of this actual module:');
my_lib.print_calling_module_path(module);

... but it forces to use an extra parameter, which pollutes the argument list of functions with a (possibly?) deductible information.

What I'm looking for

For example:

lib/my-lib.js:

const path = require('path');

exports.print_calling_module_path = function(/* no extra argument */) {
    let calling_module = .... ;  // <== How to get this ??
    console.log(path.dirname(calling_module.filename));
}

main.js:

const my_lib = require('./lib/my-lib.js');

console.log('Here is the path of this actual module:');    
my_lib.print_calling_module_path(/* no extra argument */);

Inside the print_calling_module_path() function, how can I get the calling module object, without passing it as a parameter? Maybe something dealing with the stack trace?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Check out documentation https://nodejs.org/api/modules.html#modules_the_module_object They mention require.main and require.parent properties. If it will not work for you, then use a.p's comment about using new Error().stack

over 4 years ago · Santiago Trujillo Relatório

0

I finally use new Error().stack as a.p suggested; here the final code, following the example in the question:

lib/my-lib.js:

function unique_filter(value, index, self) {
    return self.indexOf(value) === index;
}

function get_module_stack() {
    return new Error().stack.split(/\n/)
        .map(line => line.match(/\(([^:\)]*)/))  // Match lines with filenames
        .filter(match => match !== null)         // Remove null matches
        .map(match => match[1])                  // Map to the the actual filenames
        .filter(unique_filter)                   // Make filenames unique
}

exports.print_calling_module_path = function()
{
    console.log(get_module_stack()[1]);
}

However I'm not sure if this method is reliable enough to use it for production.
Any comment about it will be welcome.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda