Are node.js modules need to be wrapped inside the module pattern? - node.js

To ensure proper isolation, I tend to wrap each node.js module that I write inside a function scope:
(function() {
var express = require('express');
var jade = require('jade');
var moment = require('moment');
exports.someFunction = function() {
// do something
};
exports.otherFunction = function() {
// do something else
};
})();
I've been doing this for some time now, but I have the feeling that node.js' module system is actually doing this for me, or (in other words) that the above code is equivalent to the following code:
var express = require('express');
var jade = require('jade');
var moment = require('moment');
exports.someFunction = function() {
// do something
};
exports.otherFunction = function() {
// do something else
};
Are the two really equivalent?
In particular, I am interested to know whether is the isolation level is the same: are the express, jade or moment variables local to the module? (i.e., I'd like to make sure that they are not defined in the global scope or interfere with any other definition outside of this module).

Variables declared within a module are local to that module. It is safe to omit your enclosing function.
From the Node.js docs:
Variables local to the module will be private, as though the module was wrapped in a function

Related

In Node, why does 'require' assignment sometimes require curly brackets?

Running some tests through Chai, I noticed the tests would fail under this code:
const add = require('./addition');
//'add is not a function error' even though it's directly exported as a function
But it would pass under this:
const {add} = require('./addition');
Yet when using npm modules, everything is declared without the brackets:
var express = require('express');
var app = express();
var session = require('express-session');
And those are essentially objects with multiple properties to be accessed. Why does it work this way? Is it only function exports that must be assigned as objects explicitly?
This is known as object destructuring. Please refer the link.
For example you have exported a file called sampleFunctions.js which has following functions as exports
function function1(params) {};
function function2(params) {};
module.exports = {
sampleFunc1: function1,
sampleFunc2: function2
}
Now when you need to require it, there are two ways -
when you only need one function(using object destructuring)
let {sampleFunc1} = require('./sampleFunctions');
sampleFunc1();
In this you exposed only the required function not all of the functions exported from that file.
when you want to require all the functions from that file
let sampleFuncs = require('./sampleFunctions');
let samFunc1 = sampleFuncs.sampleFunc1;
samFunc1()

Custom module in Node.js

I am new to NodeJS programming so I was trying make simple custom module by extending one module to another which prints in console log.
ExtendMod.js
var exports = module.exports = {};
exports.tutorial = function() {
console.log("N Tutotial");
}
app.js
var Tutor=require('./ExtendMod.js');
exports.NodeTutorial = function() {
console.log("Node Tutorial")
function pTutor() {
var PTutor=Tutor
PTutor.tutorial;
}
}
console.log(require('./thirdNode.js').NodeTutorial());
I have extended ExtendMod.js in app.js.
Question: Why an empty braces after exports when we create my first module and also in app.js we didn't take exports as a variable is it global?
My output :
Node Tutorial
N Tutorial
Undefined
What is this undefined?

Send a function, module to main via object Function node.js

I work on a server in node.js, and i'm quite new to the concept.
I'm using socket.io to communicate with clients
I have many modules in my server and i try to send a function declared in a module to my main. I don't want to use exports.plugin=plugin because I try to work with the observer pattern.
I tried :
In main.js:
//Modules NPM
var express = require('express');
var observer = require('node-observer');
//Extensions JS
var mymodule = require('./mymodule');
var plugin = require('./plugin');
//Initialisation
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
...
socket.on('message', function (var1, var2) { //Come from client
socket.var1=var1;
socket.var2=var2;
observer.send(this, "Message", "varSpecification");
});
In plugin.js :
//Modules NPM
var express = require('express');
var observer = require('node-observer');
//Extensions JS
var mymodule = require('./mymodule');
var main = require("./main");
...
observer.subscribe(this, "Message", function(who, data) {
var functionToSend= new Function ("varA", "varB" ,"mymodule.function(varA, varB); socket.emit('messageOK');"); //I can't create a real function because i don't use socket.io in the module Plugin
observer.send(this, "Response", functionToSend); });
Back to the main:
observer.subscribe(this, "Response", function(who, functionReceived) {
functionReceived(socket.var1, socket.var2); //Doesn't work
});
The problem is that when I execute the function in main.js, it doesn't find mymodule and can't execute the function associated.
(ReferenceError : mymodule is not defined)
When i execute the function directly in the main.js, it works.
observer.subscribe(this, "Response", function(who, functionReceived) {
mymodule.function(socket.var1, socket.var2); //Works
});
So I guess it's a problem with the object that I send
I will be more than grateful if you can help me!
EDIT : After other tests I found the source of the problem :
var mymodule = require('./mymodule');
...
mymodule.function(a, b); //works
var functionTest= new Function('mymodule.function(a, b)');
functionTest(); //Doesn't work (mymodule is not defined)
I still want to use the second option for my project but don't know how
I used the function constructor, and i didn't know that the function is declared in the global scope.
So i had to write this to make it work :
var functionTest= new Function('mymodule', 'a', 'b','mymodule.function(a, b)');
functionTest(mymodule,a,b);
I had to pass mymodule, a and b in parameter

why are 'required variables' declared outside module.exports

I understand that functionality is scoped inside module.exports. But I always see variables declared outside. So shouldn't it be inside ?
var bcrypt = require('bcrypt');
module.exports = {
...
}
The code outside of the module.exports is not visible outside of the file. Typically includes libraries and functions used within the code you are writing. I guess you could think of this as being "private" functions / variables.
I don't know if you are writing code inside of module.exports but I prefer not to. I find this to be more readable:
var doSomethingImpl = function(){
}
module.exports = {
doSomething: doSomethingImpl
}
or
var doSomethingImpl = function(){
}
module.exports.doSomething = doSomethingImpl
or even
module.exports.doSomething = function(){
}

Node.js inherit local variables

I have a variable in my server.js, lets call it 'a'. When I require a module, it doesn't have access to the variable a. For example:
server.js
myModule = require('./myModule.js');
var a = 'Hello!'
myModule.say();
myModule.js
exports.say = function () {
console.log(a);
}
How can I make it so myModule.js can access the variables in server.js without having function arguments?
server.js:
myModule = require('./myModule.js');
global.a = 'Hello!'
myModule.say();
myModule.js:
exports.say = function () {
console.log(global.a);
}
However, please keep in mind globals are usually discouraged in Node.js (and JavaScript in general). Isn't the point of a module to encapsulate certain functionality? If so, it shouldn't depend on outside variables existing or being defined.
Ideally, you want to pass in the required information into the module via some sort of initialization function or configuration parameters.

Resources