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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't get serialized... but I would like to have a serializable configuration, as { "onendrequest" : "myfunction" }
By declaring the function in the global variable I solved the problem! Thanks!
@RicardoPeres no worries but I'm confused - the other answer didn't solve your problem but you've marked it as correct?
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(){/*...*/});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.