Modules in Node.js
A module is a file of JavaScript that one program can reuse. A program can use the same module again and again.
A module file
This file is one module. It holds one function.
function greet(name) {
return "Hello, " + name + "!";
}Use the function
This small program defines a greeting function and calls it.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Maya"));Example
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Maya"));
console.log(greet("Sam"));Key points
- A module holds code for one job.
- One file is one module.
- A module keeps its code apart from other code.
- Small modules are easy to read and to change.
- A program can use a module more than once.
In this example, the file holds one function named greet. The function takes a name and returns a greeting. The first print greets Maya. The second print greets Sam. The file is one module, and the function inside it can run again and again.
Note
A module is a file, not a folder.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is a module?