Node.js: Code Outside the Browser / Working with Modules

Module wrapper function & module caching

Whenever you write a Node.js module, behind the scenes Node wraps your code inside a function like this:

(function(exports, require, module, __filename, __dirname) {
  // your code here
});

This means every module gets:

  • exports – to export things from the module

  • require – to import other modules

  • module – metadata and reference to the current module

  • __filename – full path of the current file

  • __dirname – directory of the current file

// checkWrapper.js

console.log(__filename);
console.log(__dirname);
console.log(arguments);
C:\Users\Varsha\Documents\NodeJS\checkWrapper.js
C:\Users\Varsha\Documents\NodeJS
[Arguments] { 0: [Function (anonymous)], ... }

⚙️ Module Caching in Node.js

When you require() a module more than once, Node doesn't reload it again.

Instead, it uses a cached version for efficiency.

🔁 Explanation:

The first time counter.js is required (in fileA.js), it's executed and cached.

When fileB.js requires it again, Node returns the same cached version, so the count variable retains its value.