I would like to know what "module wrapper function" means and what it does to my code.
(function (exports, require, module, __filename, __dirname) {
});
According to the Node.js documentation,
Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) { // Module code actually lives in here });
By doing this, Node.js achieves a few things:
- It keeps top-level variables (defined with var, const or let) scoped to the module rather than the global object.
- It helps to provide some global-looking variables that are actually specific to the module, such as:
- The module and exports objects that the implementor can use to export values from the module.
- The convenience variables __filename and __dirname, containing the module's absolute filename and directory path.
Essentially, this wrapper is used to configure your module, and it enables the use of the variables exports
, require
, module
, __filename
, and __dirname
.
OP also mentions the process
and global
variables.
process
object gives information about, and control over, the current Node.js process.
exit
and uncaughtException
to manage the Node process. process.abort()
to end the current process.process
global
provides a system for accessing and setting global variables.
global.something = true
in one module, in another module you can access something
and it will be true
(without having to export it).global
documentation.You can edit the wrapper, too:
let Module = require('module');
Module.wrap = (function (exports, require, module, __filename, __dirname) {
// What you want the new wrapper to be.
return Module.wrapper[0] + exports + 'console.log("This is the wrapper.");' + Module.wrapper[1];
});
I think, I'm little late on this post but I'd like to share my 2 cents here.
So the expression you have written is IIFE (Immediately Invoked Function Expression).
Basically, your code in a (Node)file is wrapped inside this particular function. When someone requires this file, IIFE runs automatically and provides you objects such as module.exports, exports, __dirname, __filename.
These objects are not global but local to your module (file). And these are made available by this IIFE function. Using this object can export your module.
Link to the documentation is already provided in above answer, that should help.
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