Nodejs: completion of the entire script in a function call

I wrote modules in nodejs as follows:

module.exports = function (logger, db, external,constants) { return { //something } } 

Recently, someone from my team suggested that the entire script should be wrapped in a function to avoid global confusion of variables, for example:

 (function () { 'use strict'; module.exports = function (logger, db, external,constants) { return { //something } } }()); 

I understand that this practice is commonly used on the client side. But on server side in nodejs is this required? I think that nodejs really does not have a global scope, and only module.exports is the one that is available really regardless of what we write in the script file (of course, this is not enough).

+6
source share
2 answers

No, IIFE is not required with Node.js.

They can be useful for any script that can be used in multiple environments ( UMD ).

But each module / file executed by Node.js is provided with a โ€œmodule areaโ€ similar to that provided by IIFE, as described in the Globals section :

In browsers, the top-level area is a global area. This means that in browsers, if you are in the global scope of var something , a global variable will be defined. Node is different. The top-level region is not a global region; var something inside the Node module will be local to this module.

Although, there is still a global scope with Node.js. When a module creates a global one, it will be available in other modules used by the same process.

 foo = 'bar'; // lack of `var` defines a global console.log(global.foo); // 'bar' 
+11
source

You actually already do this.

What he suggests is to wrap the entire script in a function like this:

 function () { } 

It's all. Nothing special. Of course, in regular javascript, a function definition simply defines a function, and the code inside the function does not run. Therefore, to automatically run a function, you transfer it to the context of the expression and call it:

 (function () { })() 

However, in node.js you do not need to do this. Instead, you can simply call the function when you need a module. So in node.js, this does the same in terms of creating a private scope:

 module.exports = function () { } 

So, tell your friend that you are already completing the entire script in the function.

This is perhaps the first time that I see harm in the name of things and design templates. In this case, your friend is thinking about IIFE. But IIFE is nothing special. IIFE does not create a closed area. It performs the functions that create the area. IIFE is just a means for a function to call itself. That is why I prefer to call it a self-service function, so as not to give it a sense of magic that can make some people perceive it as something special.

+1
source

Source: https://habr.com/ru/post/975957/


All Articles