Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda