1

I have a Node.js library file that is required by my Node.js application file, exporting a function.

In the application file I am calling the exported function, passing it some parameters, and it is working fine.

In one of the parameters, I would like to send the name of a function that is declared in the application file; this is so that the parameters can be JSONified. However, the code in the library file cannot find the function by name, because it exists in another file (the application one).

I know I can get over this by passing a pointer to the function, instead of its name, but because of serialization (functions cannot be serialized), I would like to pass the name.

I cannot just export the function from the application file and import it in the library file because that would be a circular reference, and, of course, the library file does not need to know about the application one.

What is the recommended pattern for dealing with this kind of situations?

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • pass it as reference and use .name property. See http://stackoverflow.com/questions/2648293/javascript-get-function-name – Roland Starke Nov 23 '15 at 13:35

2 Answers2

1

The recommended pattern is still to probably pass a function object - why does your function get serialized when you pass a reference to it?

A really easy alternative would be to just define your function in the global scope but this pollutes the global scope and goes against the really awesome encapsulated way we write nodejs code:

global.yourCallback = function() { ... }

and now the string yourCallback will work.

David Zorychta
  • 13,039
  • 6
  • 45
  • 81
1

You could register the function with your library in advance, in a kind of configuration-stage or when loading/defining the function:

var mylib = require('./mylib')

function myfunc(){
     // ...
}
mylib.register('myfunc', myfunc);

Assuming the registration is done at start-up then the library and consumers of the library would be able to refer to it as 'myfunc'.

Other libraries/frameworks such as AngularJS do similar things, e.g.:

angularModule.controller('MyController', function(){/*...*/});
Supr
  • 18,572
  • 3
  • 31
  • 36