How to call exported function inside the same file - node.js

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'

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

External function calling for parent's "this" scope

I have two .js files: root.js and external.js
root.js
import myExternalFunction from 'external.js'
class Parent {
constructor(){}
parentFunction = () => {
console.log('I was called from an external function using "this."')
}
}
external.js
export default myExternalFunction = () => {
this.parentFunction()
}
Currently I receive an error about it not being a function, or no access to 'this'.
How do I import external functions that want to use the 'this' scope from which they are being called?
How do I import external functions that want to use the 'this' scope from which they are being called?
It doesn't have anything to do with how you export/import the function.
There are two things you need to consider:
functions that want to receive their this value dynamically must not be arrow functions, so use
export default function myExternalFunction() {
this.parentFunction()
}
as usual, the function must be invoked in the right way to get the expected this value. There's no magic that passes the current this value in the scope of the call to the called function. You'll have to do something like
import myExternalFunction from 'external.js'
class Parent {
constructor(){
this.method = myExternalFunction;
this.parentFunction = () => {
console.log('I was called from an external function using "this."')
}
}
}
const example = new Parent;
example.method() // an invocation as a method
myExternalFunction.call(example); // explicit using `call`

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

How to pass this to require() in NodeJS?

What's the best way to pass thisArg to a require()d module?
I want to do something like this:
index.js
function Main(arg) {
return {
auth: auth,
module: require('/some/module')
}
}
module.js
module.exports = {
someMethod: function() {...}
}
Then, in my code somewhere I call Main(), which returns the object.
So Main().auth exists, cool. But how do I access it from Main().module?
The thisArg in Main().module.someMethod() points to the module itself.. but I need the parent.
Is there any way to do this without using new keyword, functions and prototypes?
EDIT:
Thanks for all the answers guys! Some additional info:
Main() is the module what I wanna require() and use in my app. The "module" Main tries to import is actually just sub functionality of Main, it's just a part of code which I moved to a separate "module" to better organize the code.
So a better example would be:
function RestApi(param) {
return {
common_param: param,
commonFunc: function() {...}
endpoint1: require('/some/module'),
endpoint2: require('/some/module2'),
endpoint3: require('/some/module3')
}
}
And my app would use it like this:
RestApi = require('./RestApi')
RestApi().endpoint1.someHTTPCall(...)
But inside someHTTPCall(), both "common_param" and "commonFunc" should be accessible via thisArg, like this.commonFunc().
So this is kinda a general question, how do you merge multiple modules using require() properly, so "this" would point to the right object (i.e.: the parent)
I know this could be achieved using Function.prototype and inheritance, just would like to know if there is a simpler way.
The best I found so far is something like this:
var _ = require('lodash');
function Module(auth) {
this.auth = auth || {};
}
Module.prototype = {
endpoint1: function() { return _.extend(require('./endpoint1'),{auth: this.auth, commonFunc: commonFunc})}
}
function commonFunc() {...}
However, this is not ideal, since RestApi.endpoint1() would create a new the object on every call.
Is there a better way to handle this?
Thanks in advance!
Create own "require" module with auth param and allways use it.
project/module/require2.js
module.exports = function(path, auth){
if (!check(auth))
return null
return require(path)
}
You could change the module to return a function, like this:
// some/module.js
module.exports = function(mainModule) {
var main = mainModule;
return {
someMethod: function() {
main.doSomethingElse();
}
}
}
Then require it passing the main object:
function Main(arg) {
var main = {
auth: auth,
other: stuff,
};
main.module = require('/some/module')(main);
return main;
}

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