Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

module

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).

like image 861
Itay Maman Avatar asked Feb 03 '14 15:02

Itay Maman


People also ask

Does the Node wrap all the modules?

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.

What is Node module wrapper?

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.

How modules are loaded in NodeJS?

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.

DO built-in modules in NodeJS need to be installed?

js Built-in Modules. Node. js has a set of built-in modules which you can use without any further installation.


1 Answers

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

like image 90
James Allardice Avatar answered Oct 05 '22 14:10

James Allardice