Day 82 Node.js Modules

Yesterday left off with learning what a module is. A module is a reusable block of code whose existence does not accidentally impact other code.

Today first we downloaded node.js from their website and made sure our computer had it installed with a command “node -v” in the command line. This returns the version of node.js is installed.

Next, we created another JavaScript file in our IDE. We created a simple console.log module then pulled it. In order to pull it, we need to use a function called “require()”. Within the parameter is a string which contains the location or the name of a module you’d wish to import. Essentially require is saying I need this… I require this.

The require function must be placed in the JavaScript file you are calling within node.js. For example, if you have a module in app.js you would place the require() function into your main.js since you are importing from app.js.

That was essentially my first module created in node.js. The course took it a step further by changing the console.log module into a function. By changing the module into a function I discovered that you cannot call the function in the main.js file even though you have the module imported. That’s the beauty of modules it doesn’t allow you to impact other code. This allows for fewer errors to be made if fewer things affect each other.

However, there is a way to get certain functions and object properties from a module. There is a special function you can use within the module file called module.exports. Then I set the export function equal to the function or object that you want to pull data from.

The rest of what I learned was a review of JavaScript fundamentals like yesterday. Today JavaScript review was about first-class functions, objects, JSON, prototypes, and by reference.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up ↑

%d bloggers like this: