user module - node js - object

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
};

Related

Executing a function knowing only its name in node

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']()

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.

Getting around async issue in node.js application command line

My application is a simple mysql client used from command line - it connects to database and makes few queries to get information from database. Mysql functionality is encapsulated in a class and problem is since calls to mysql server is async (understandably) - the code flow reaches end of application.
And I am unable to refer to 'this'(Mysql) inside a method of Mysql class.
How do I get around this problem ?
Below is my code.
//CLASS
function Mysql(config) {
//...
}
//METHOD
Mysql.prototype.getDbInfo = function (cbk) {
this.showTables(function(e,r) {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(this.configVar);
});
}
module.exports = Mysql;
//CLASS OBJECT
var test = new Mysql(config);
//METHOD INVOKE
test.getDbInfo(function (err,results) {
//...
});
Every time that you jump into a callback function you are loosing the scope of the this object. There are different ways to work around it.
Assign this to another variable
The first solution is to assign the this object to another variable (e.g.: that, self). When you assign one variable to another and the first variable is an object then you keep the reference to the original object and you can use it within the callback. Something like that:
Mysql.prototype.getDbInfo = function (cbk) {
var self = this;
self.showTables(function(e,r) {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(self.configVar);
});
}
Bind the this object to the function
You can bind the this object to the function and like that you set the this keyword set to the provided value (in your case the scope outside of showTables function). You can read the documentation of this and you will be able to understand more:
Mysql.prototype.getDbInfo = function (cbk) {
this.showTables(function(e,r) {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(self.configVar);
}.bind(this));
}
Use es6 arrow functions
It is more or less the same solution like the first one. If you use a transpiler you will find out that it is translated like the first solution:
Mysql.prototype.getDbInfo = function (cbk) {
self.showTables((e,r) => {
// >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
console.log(this.configVar);
});
}

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
}
}
};

Resources