Executing a function knowing only its name in node - node.js

Let's assume I want to execute a function in node but I have only its name (a string).
If the function is defined in a package (which has been imported) I can do something like this
require("lodash")["add"](1, 2);
If the function is defined in another file and exported, I can do something like this
a-function.js
export function aFunction() {
return console.log("I am a function");
}
anotherJsFile.js
require("./a-function")["aFunction"]();
If the function thuogh is defined in the same file where I have the code that wants to call it, I have found only this way to make it work
export function anotherFunction() {
return console.log("I am another function");
}
// the null check guard is added to avoid an "object may be null" Typescript error
(this || {})["anotherFunction"]();
Is there a better solution to call a function by name when the function is defined in the same file?

You can stash your functions in an object that permits finding them by name.
const call = { foo }
function foo() {
console.log('foo was called.');
}
call['foo']()

Related

How to stub an inner function and set a variable value

This is one of the more complex scenarios I've encountered yet. I have a function that I need to test, this function is nested in a complex puzzle of functions. I need to stub this function, and set a value inside the variable inside.
For reasons I'm not allowed to share here, the variable inside the publishEvent() method is undefined during test run, I need a way to set the value for this variable during test in order for me to test the if block of code in the function.
I summarized the whole file because I can't share the code here due to NDA, sorry if the question is not detailed enough. Maybe using sinon I can directly set the value for this variable in the publishEvent function.
function emitEvent() {
async function publishEvent() {
const variable = library.fetchData()
if (variable) {
// do something
}
}
return Promise.resolve(publishEvent())
.then(() => { })
.catch(() => null);
}
function requestSuscription() {
return getAllSubscriptions()
.then((results) => {
return Promise.map(results, () => emitEvent())
})
}
function getAllSubscriptions() {
return new Promise()
}
function requestOtherSubscription() {
console.log('other thing requested')
}
module.exports = { requestSuscription, requestOtherSubscription }
I know I can stub the requestSuscription, requestOtherSubscription functions and it works, but how can I stub the publishEvent and set the variable value?
You need a way of controlling what library.fetchData() outputs. Either you need a way of injecting a substitute for that library (easiest option) or you need to employ a link seam (environment dependant, requires extra lib) - substituting the library with a fake one at the module loading level.
You can check out this SO answer to a nearly identical question for details.

How to call exported function inside the same file

I have faced a problem regarding calling an exported function inside the same file.
When I call it then the error shows the following.
UnhandledPromiseRejectionWarning: ReferenceError: findOrCreateMedia is not defined
where findOrCreateMedia is my function. How can I fix this?
Try this:
function functionName() { ... };
exports.functionName = functionName;
functionName();
This is happening because you are losing your this object reference inside your calling function.
For eg:
module.exports.a = function () {
return true
}
module.exports.b = function() {
return this.a();
}
here you will get the issue because when you call this.a(), it is referencing the this object of the b function.
To solve this your have to store your this object reference somewhere or use the arrow function, because the arrow function doesn't have there own this object so it will always reference the outer this object
To solve this, modify your function like this
module.exports.a = function () {
return true
}
module.exports.b = () => {
return this.a();
}
you can also ES6 import/export function:-
const someFunction = (){
...
}
export default someFuntion ( in the case on single function)
When you want to export multiple functions
export { someFunction1, someFunction2}.
Now the place where you want to import
import somFunction from 'filelocation' ( note in case of default exports you need to use the same name of the function)
In the case of multiple functions.You can change the function name but keep in mind the order of exports and imports.
import { myFunction1,myFunction2} from 'fileLocation'

Why is the middleware named in the below example [duplicate]

I have a major problem with profiling in javascript with anonymous functions, I have always many anonymous functions - most of them are callbacks - and It makes analyzing results of profiler very hard for me.
Finally I decided to use named functions for callbacks, like this:
var f = function(callback) {
// Do something ...
callback();
}
f(function named_function() {
console.log('Sample callback function!');
});
I want to know that will I have any problems after making this change in my codes?
And will this type of function definition and passing reserve the name (named_function) anywhere?
The name will only be available inside the scope of the named function expression.
But there is a problem in IE 8 and lower. It will leak out to the outer scope, and will actually create a different function object, so you should nullify it if that's a problem.
f(function named_function() {
console.log('Sample callback function!');
});
var named_function = null;
See this article for more information: Named function expressions demystified
Or you could create it like this to solve the IE issue.
f(function() {
return function named_function() {
console.log('Sample callback function!');
};
}());
But that's a little ugly.
If you pass anonymous functions like that, the name will exist inside the function itself.
It will not exist in any other scope.
var f = function(callback) {
// Do something ...
callback();
}
f(function named_function() {
console.log(named_function); // Logs the function
console.log('Sample callback function!');
});
console.log(named_function);​ // Error: named_function is undefined
You don't have to complicate things.
Just name the function when you declare it
var foo = function foo(){};
Defining a named callback in a scope will cause it to be visible only in that scope. I would therefore conclude that there shouldn't be any naming conflicts. For example, the following code runs as expected:
(function named_callback() { console.log("Callback 1"); })();
(function named_callback() { console.log("Callback 2"); })();​
Actually, you're still creating an anonymous function expression and assigning it to a local scoped variable f. Go for
function f( callback ) {
callback();
}
f( named_function );
function named_function() {
console.log('Sample callback function!');
}
That way, you're even avoiding the named function expression memory leak in <= IE8, plus since you're no longer creating a function expression but a *function declaration, you can even access f within the body.

Node modules usage error

Ive node moudle which i need to export two functions and get to both of the function a parameter arg1,I try with the following I got error,what am I doing wrong here ?
UPDATE
Ive two method inside module
1. I need to expose it outside and to call it explicit from other
module with parameter
like
require('./controller/module')(functionName1)(parameter);
another function(functionName2) in this module which I need to call it explicit with two parameter ,how should I do it right?
It is not very clear what you want to do, but i think you want something like that:
module.exports = function (arg1) {
return {
server: function (params1) {
//do something with arg1 and params1
},
proc: function (params2) {
//do something with arg1 and params2
}
}
};
And using the module:
var arg1 = 'whatever'
var myMod = require('myMod')(arg1);
myMod.server();
myMod.proc();
Option 2
If i look at your new example
require('./controller/module')(functionName1)(parameter);
you need module that exports a function that returns another function (Higher Order Function).
So for example:
module.exports = function(functionName1) {
if(functionName1 === 'server'){
return function server(parameter){
//do your stuff here
}
}
if(functionName1 === 'proc'){
return function proc(parameter){
//do your stuff here
}
}
};

user module - node js

i have a question regarding defining objects in modules.
lets say i have a module:
/*---obj----*/
function A (param){
this.parm=param;
function func(){
//do somthing
}
}
exports.func=func;
/*---file.js----*/
obj=require('obj');
function fileFunc(A){
A.func();//with out this line it works fine
A.param=2;
}
}
for some reason it does not recognize the function in the object A. it recognizes the object A and its different vars, but when it comes to executing the function it gives the msg:
TypeError: Object # has no method 'func'
i tried also to export the function in A by:
exports.A.func=A.func
or
exports.func=func
neither works..
does someone have a clue?
thanx
matti
The function you defined inside of A is local only to that function. What you want is
function A(param) {
this.param = param;
}
A.func = function() {
// do something
};
But if you are treating A as a constructor then you'll want to put that function in A's prototype
A.prototype.func = function() {
// do something
};

Resources