1

How are private functions and data of modules accessed after loading the module?

I know that the require function loads the module and returns the module.exports object which contains some public objects or functions, but how are the other 'private' parts of the code in the module accessed? where is it located in the memory?

Markus Hütter
  • 7,796
  • 1
  • 36
  • 63
OMar Mohamed
  • 303
  • 3
  • 10
  • To be clear, you're wondering how the private functions / data in the module is used **in the module**, right? You can't use it from outside the module, that's why we call them "private." – T.J. Crowder Jul 09 '16 at 13:11

2 Answers2

1

TL;DR - Code in NodeJS modules can continue to access the non-exported things they define within the modules because they and the functions they define close over that data.

Details:

NodeJS modules are effectively big functions that get called by NodeJS when you require them. (They're only called once, regardless of how many times they're required.) A function call in JavaScript sets up an execution context and any functions created within that context close over the context (they have an enduring reference to it and its contents). The execution context survives in memory as long as anything has a reference to it, even after the "function" has returned. The functions created within the execution context are "closures".

So say you have a module foo:

var privateData = Math.random();
function publicFunction() {
    console.log("The private data is " + privateData);
}
module.exports.publicFunction = publicFunction;

and you require it:

var foo = require("foo");
foo.publicFunction(); // Displays the random number

That's analogous to having a function that returns an object:

function fooModule() {
    var privateData = Math.random();
    function publicFunction() {
        console.log("The private data is " + privateData);
    }
    return {
        publicFunction: publicFunction
    };
}

that you call:

var foo = fooModule();
foo.publicFunction(); // Displays the random number

The same mechanism is at work in both places.

More to explore:

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The consumer of a module can only interact with its API, a.k.a. what it exports. You cannot access its private functions and state directly. That would violate encapsulation.

The module itself can do it for you. Whatever functions are exported by a given module can interact with anything in that module.

If you come from a Java or C# world, think of it like public/private methods on a class. In a node module, everything is "private" unless it is exported.

Brandon
  • 9,822
  • 3
  • 27
  • 37