Modules, Exports, and Require

Modules:

  • Reusable block of code whose existence doesn't accidentally impact other code.

  • Code that doesnt affect the rest of the node framework

greet.js

var greet = function() {
    console.log('hello');
};

greet();

app.js

require('./greet.js')

commandline

node app.js // hello
  • Tells where to look

  • Allows us to individualize files or modules

  • Notice that this doesnt allow us to use any of the functionalities in app.js (its not an #include).

    • This is by design by module, the file is protected and self contained.

    • But there is a way to make it available

greet.js

app.js

commandline

How does it really work?

  • Modules use the advantages in variable scope within functions / immediately invoked functions.

  • Require:

    • Wraps the code you write within a function expression.

    • Everything you write in a node module is wrapped within a function expression

    • Require returns the module that you write.

      • Within your own module, if you've exported anything, you basically are changing back your own module that eventually becomes returned.

Require more than one object

  • Build a new folder than the require that folder, which can contain multiple contents.

app2.js

app3.js

index.js

app.js

commandline

Incorporating JSON with Require

app2.js

app3.js

index.js

app.js

commandline

Module Patterns

Pattern 1

  • We can also do something like

  • Here we're essentially building off the require object that is returned.

Pattern 2

app4.js

app.js

  • Notice that even though we've created a new object, the modifications made to greet3 as an object, affected all subsequent call for newly created objects. The all essentially become the same object.

    • This is because the changes are cached within the require function.

To Avoid This

  • Simply return the function constructor entirely and avoid creating new objects there

app4.js

Pattern 3

app4.js

app.js

  • Why this is useful:

    • greeting is encapsulating within app4.js, and the only thing we export is the greeter function.

    • This means we do not have access to greeting. The variable essentially becomes private to the module - which is good because it wouldn't be a good idea to change it within the application.

Require Core Native Modules

  • There are already modules that are built within node that are native to the functionality of node.js itself. AKA node api.

    • Some are global

    • Others require 'includes'

  • All of this can be found within the api documentation for node.js

Last updated

Was this helpful?