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).
It implies the file name of the current module. It refers to the directory name of the current module. Note that every file in Node. js will wrap every file that it executes.
Use of Module Wrapper Function in NodeJS:It provides some global-looking variables that are specific to the module, such as: The module and exports object that can be used to export values from the module. The variables like __filename and __dirname, that tells us the module's absolute filename and its directory path.
These modules can be loaded into the program by using the require function. Syntax: var module = require('module_name'); The require() function will return a JavaScript type depending on what the particular module returns.
js Built-in Modules. Node. js has a set of built-in modules which you can use without any further installation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With