Modules in Node.js | Lecture 4
Here are
notes on Modules in Node.js:
Modules in Node.js
What are Modules?
- Modules are reusable blocks
of code that help organize functionality into separate files and
libraries.
- Node.js uses CommonJS
modules by default.
Types of Modules in Node.js:
- Built-in Modules:
- Pre-installed modules in
Node.js.
- Examples: http, fs, path, os, events.
- User-defined Modules:
- Custom modules created by
developers to structure application code.
- Third-party Modules:
- External libraries
installed via npm.
- Example: express, lodash.
Using Modules in Node.js:
- Importing a Module:
- Use the require() function to load a module.
- Syntax:
o const moduleName = require('module-name');
- Exporting from a Module:
- Use module.exports or exports to expose functionality.
- Syntax:
o // In a module file (example: math.js)
o module.exports = {
o add: (a,
b) => a + b,
o subtract:
(a, b) => a - b,
o };
- Using the Exported Module:
- Import and use the exported
functions or objects.
o // In another file (example: app.js)
o const math = require('./math'); // './' indicates a
relative path
o console.log(math.add(2, 3)); // Outputs: 5
Built-in Modules Examples:
- fs (File System Module):
- Handles file operations.
o const fs = require('fs');
o fs.writeFileSync('example.txt', 'Hello, Node.js!');
o console.log(fs.readFileSync('example.txt',
'utf-8'));
- http (HTTP Module):
- Creates web servers.
o const http = require('http');
o const server = http.createServer((req, res) => {
o res.write('Hello from the HTTP module!');
o res.end();
o });
o server.listen(3000, () => console.log('Server
running on port 3000'));
- path (Path Module):
- Provides utilities for file
and directory paths.
o const path = require('path');
o console.log(path.basename('/folder/example.txt'));
// Outputs: example.txt
- os (Operating System Module):
- Provides system-related
information.
o const os = require('os');
o console.log(os.platform()); // Outputs: platform
(e.g., 'linux', 'win32')
Creating and Using a Custom Module:
- Create a Module:
- File: greet.js
o function sayHello(name) {
o return
`Hello, ${name}!`;
o }
o module.exports = sayHello;
- Use the Module:
- File: app.js
o const greet = require('./greet');
o console.log(greet('John')); // Outputs: Hello,
John!
Third-party Modules Example:
- Install and use the lodash library:
·
npm
install lodash
·
const _ =
require('lodash');
·
const arr
= [1, 2, 3, 4, 5];
·
console.log(_.shuffle(arr));
// Outputs: shuffled array
Advantages of Using Modules:
- Promotes code reusability.
- Improves maintainability and
organization.
- Encourages modular design.
Let me
know if you'd like more examples or in-depth explanations!
Comments
Post a Comment