Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
Desde una función, ¿cómo obtener detalles sobre el módulo que realmente llamó a esta función?

En una función de uso general, me gustaría obtener información sobre el módulo que llama a esta función (especialmente el directorio base, que se puede recuperar dentro de un módulo con path.dirname(module.filename) ).

lo que probé

Por ahora, la única forma que encontré para hacerlo es agregar un module como parámetro para la función:

lib/mi-lib.js :

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

principal.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);

... pero obliga a usar un parámetro extra, que contamina la lista de argumentos de funciones con (¿posiblemente?) información deducible.

Lo que estoy buscando

Por ejemplo:

lib/mi-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)); }

principal.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 */);

Dentro de la función print_calling_module_path() , ¿cómo puedo obtener el objeto del módulo de llamada sin pasarlo como parámetro? ¿Quizás algo relacionado con el seguimiento de la pila?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Consulte la documentación https://nodejs.org/api/modules.html#modules_the_module_object Mencionan las propiedades require.main y require.parent . Si no funciona para usted, use el comentario de ap sobre el uso de new Error().stack

over 4 years ago · Santiago Trujillo Report

0

Finalmente uso new Error().stack como sugirió ap; aquí el código final, siguiendo el ejemplo en la pregunta:

lib/mi-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]); }

Sin embargo, no estoy seguro de si este método es lo suficientemente confiable como para usarlo en la producción.
Cualquier comentario al respecto será bienvenido.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!