DEV Community

Harsh Gaur
Harsh Gaur

Posted on

Node.js wrapper functions

Suppose you are asked what would happen if you run a file which has only one line of code console.log(arguments) in the Node.js environment. What would be your first guess?

You might think that it would return a reference error saying arguments is not defined. But that is not the reality. If you actually try to run it, it would give you some output that would look like the one shown in the image below

Node.js wrapper functions

In Node.js every file has a wraps every file it executes with a function and thus console.log(arguments) prints the 5 arguments that node passes to that wrapping function.

To understand it better here is a commented code which tells how it happens.

Node.js wrapper functions

Here, as we see the wrapper function has 5 arguments namely,

  1. export
  2. module
  3. require
  4. __filename
  5. __dirname

Interestingly, you might have used some of these here and there but, like me, you have just now figured out why it happens.

  • module and export can be used to change current module itself. Module has an object called exports which has a default value of {}
  • require is used to import other modules into your file/app
  • __filename and __dirname are the path of the current file and the current working directory

Here are some of the articles that I found quite helpful to understand and play along with the wrapper functions.

Everything you should know about module and exports

Changing the default Node.js wrapper

Discussion (0)