This site runs best with JavaScript enabled.

Modules in Node

December 05, 2017

Video Blogger

What are modules when it comes to Node and why do we use them?

In node in your module system, each file is a separate module. Why? It's an easy way to keep track of things. Our brains can conceptualize modules pretty well.

Think of a module called 'redbutton' that could have your red button inside it--and nothing else.

Modules are also reusable chunks of code. You can use that redbutton module again in different areas. Although everything that lives in that module should stay in that model, you can include that module into another module by using the require function. This means we don't have to worry about code that accidentally impacts other code and yet we can add certain code where we want it.To include a module in another file, we use the require() function with the name of the module. For example:

var redbutton = require('redbutton);

1var redbutton = require('redbutton);

Require is a function and you pass it the location of the module that you want to import into your desired file. By using the require function above you're really just saying, “Node, go get this module for me and make it available in my current file.” You've invoked this function, given it a string with the name of the file where that module lives, and now Node is grabbing this file. To make functions (as if the redbutton were a function) inside other modules like the redbutton example work, you have to explicily make them available in other files. You can do this with

1Module.exports = redbutton;

Now the redbutton module exposes this function, and makes it available outside just the module it lives in. 

Share article


Hi, I'm Madison. I'm a self-taught software developer currently working @Mediavine. Sign up to my email list to get tips on learning how to code and a copy of my free coding course.