Modules
Learn how modules work in Node.js.
We'll cover the following...
What is a module?
Let’s explore what a module is in the context of Node.js.
Each separate file is treated as a module in Node.js. The most common use of modules is to use code or functions across different modules. This allows us to keep our code organized, as each module can serve a specific purpose. This may seem like a circular argument; let’s see what we mean by this in the code widget below. Be sure to go through all three files.
Press + to interact
index.js
square.js
shape.js
const square = require('./square.js')const shape = require('./shape.js')console.log("Area of the square is" , square.area(5))console.log("Perimter of the square is" , square.perimeter(5))const myShape = new shape("Hexagon", 6)myShape.info()
require
require
is used to import modules, JSON files, and local files. It is passed a relative path as a string. In our case, we have imported both of our modules on ...