Calling local functions in node.js - javascript

js files index.js and utils.js
I have tried to do the module export solution with no luck.
To call a function in utils.js from index.js I write a the function in utils as
export.functioname = function(parms) {
...
};
If i want to call the same function internally from utils.js i can do it i have to write another identical function as:
var functionname (parms) {
...
}
How can i get around this and only have one function to be called externally and internally?

You can use:
var yourfunction = function(param){
console.log(param);
}
exports.yourfunction = yourfunction;
yourfunction("Works");
Which prints:
"Works"

Functions can be saved to variables
var moo = function(parms) {};
export.functioname = moo;
or
function moo(parms) {};
export.functioname = moo;
works aswell because of js closures

Related

Node js: Call internal function in module.exports

I am writing a module that needs to call internal functions within the module and make use of variables in the constructor. To call these functions internally I could either use the variable mycode or use the keyword this. However using mycode means using a global variable and this can be overwritten by parts of my functions. This is a simplified model of my module's structure:
// app.js
const MyCode = require('mycode.js');
var mycode = new MyCode();
mycode.function1($(html));
// mycode.js
module.exports = class {
constructor() {
this.alertUrl = true;
}
function1(html) {
html.find('a').each(function () {
var url = $(this).attr('href');
this.function2(url); // this is now overridden by jquery
});
}
function2(url) { if (this.alertUrl) alert(url); }
}
I am looking for a solution that would work like myModule.function2(url);, where myModule is only available to functions inside the module.
You can use an arrow function instead, so that the this reference is inherited from the outer scope, rather than being altered by the each callback:
html.find('a').each((_, elm) => {
var url = $(elm).attr('href');
this.function2(url);
});
Another (less elegant) option is to save a reference to the instance before calling the each:
function1(html) {
var self = this;
html.find('a').each(function () {
var url = $(this).attr('href');
self.function2(url);
});
}
The problem doesn't really have anything to do with modules, just the calling context of functions.
you can use async function with export like this...
const function_name = async () => {
};
export default function_name ;

How do I use function from same module?

Below is my example, i create a .js file let other .js file can use it as a Helper.
var Helper = {
print: function() {
console.log("test");
},
show: function() {
print();
}
}
module.exports = Helper;
In other .js file I can include Helper file like below
var Helper = require('./Helper.js');
Helper.print(); // i will get "test" on console.
However, if I do like blow, it cannot find print function in same Helper file.
var Helper = require('./Helper.js');
Helper.show();
What can I do to use functions which from same Helper js file?
This doesn't really have anything to do with modules or files.
The function is stored on a property of an object. It isn't an in-scope variable.
You need to either:
Refer to the object (this.print()) (see also How does the this keyword work?)
Make it an in-scope variable
Such:
function print() {
console.log("test");
};
var Helper = {
print: print
show: function() {
print();
}
}
module.exports = Helper;

understanding require() with module.exports with javascript and browserify

I am a c++ programmer at heart and I'm currently being thrown into the deep end with javascript and asked to swim very quick. I am using browserify so I am able to use the require function that node.js uses to get get access to code in other files. Now everything I have done seems to be working fine, I am just unsure that I am doing it correctly.
//a.js
module.exports = function(){
alert("hello world");
}
//b.js
var myClass = new MyClass();
module.exports = myClass;
//c.js
var a = require("./a.js");
a();
var b = require(./b.js");
b.prototype.test = 555;
//d.js
function () {
var a = require("./a.js");
a();
var b = require(./b.js");
assert(b.test === 555);
}
function () { // duplicated require called inside same file but different function
var a = require("./a.js");
a();
}
So in every function and every file I want to use a.js do I have to put the require call? Seems like it will get a bit convoluted. Is there a better way to do this? Also assuming that c.js is ran before d.js will the assert pass or does it result in a copy being created of myClass so the objects are different between C and D?
Thanks for any help.
The result of require function is cached, so it would be the same only within a single process.
By the way, I cannot understand why you require a.js twice. Why not just do
//d.js
var a = require("./a.js");
function () {
a();
var b = require("./b.js");
assert(b.test === 555); // success!
}
function () { // no dupes!
a();
}

NodeJS: module.exports property is not a function

I have the following in a module file:
module.exports = {
myfunc: myfunc
};
var myfunc = function(callback){
callback(err,reply);
};
In an other file I got the reference to that module
var mymodule = require('./modules/mymodule');
mymodule.myfunc(function(err, reply){ ... });
When I call the mymodule.myfunc() I get an error saying "property 'myfunc' is not a function".
This happens only with exported functions. The same module exports some 'string' fields and these are working just fine.
When you assign module.exports, the myfunc function is still undefined. Try to assign it after declaring it:
var myfunc = function(callback){
callback(err,reply);
};
module.exports = {
myfunc: myfunc
};
To preserve your original ordering of module.exports at the top of your file, change your var myfunc initialization to a function myfunc declaration so that the latter is hoisted.
module.exports = {
myfunc: myfunc
};
function myfunc(callback){
callback(err,reply);
};
Declarations are hoisted, but initializations are not, which is why your original example did not work. w3schools has a practical description of JavaScript Hoisting.
Another scenario where i found this annoying issue was if explicitly imported only the function that my consumer needs
Say for example your exported modules looks like below
module.exports = {
func1 : async function func1(){}
func2 : async function func2(){
await this.func1(); // causes error : func1 is not a function
}
}
Now your consumer of above module looks like below:
const { func2 } = require('../theExportedModules');
//above only imports func2 but not its dependents and is not initialized
await func2(); //func2 called
Now func2() gets called from your consumer but func2() will not be able to call the func1() because it finds that func1() is not a function. Code breaks!
solution import entire modules:
const theExportedModules = require('../theExportedModules');
we could also just import func1 as well but then it would be an unused variable and we would get a warning for that.

What does `var MyConstructor = function MyConstructor()` do?

What's the difference between:
var NodestrapGenerator = module.exports = function NodestrapGenerator() {
yeoman.generators.Base.apply(this, arguments);
// more code here
};
and:
var NodestrapGenerator = module.exports = function() {
yeoman.generators.Base.apply(this, arguments);
// more code here
};
I'm trying to write my yeoman-generator's index.js in coffeescript, but apparently the second snippet isn't the same because it's not working! Thanks!
var NodestrapGenerator = module.exports = function NodestrapGenerator() { ... };
This is a named function called "NodestrapGenerator", assigned to variable NodestrapGenerator.
var NodestrapGenerator = module.exports = function() { ... };
This is an unnamed function aka. anonymous function, which gets assigned to variable NodestrapGenerator.
In the end, they're both referencing the same function, so no difference which way you write it.
See this for more explanation: var functionName = function() {} vs function functionName() {}
As to why it's not working, its probably because the code is looking for the named function NodestrapGenerator to verify that it's the function it should be using, not some random anonymous function.
FYI, function has a property name which will get set to "NodestrapGenerator" in named function (first example), but will be empty string "" in anonymous function (second example). (See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/name)

Categories