1) Modules in Node Js
1) In Node Js, modules are reusable blocks of code that encapsulate related functionality.
2) Modules allow you to organize your code into separate files and directories, making it easier to manage and maintain your projects.
3) We can define modules in separate files and then import and use them in other files using the 'require()' function (User-Defined Modules).
4) There are two types of modules - User-Defined Modules and Predefined Modules (Built-in Modules)
1.1) What are User-Defined Modules?
Definition - User-defined modules are created by the developers to encapsulate and reuse the code across their own applications. These modules are typically stored in separate files within the applications's directory.
Developers can create their own modules and export them using the "module.exports".
The same modules can be imported and used in other parts of the application using the "require()" function.
The same modules can be imported and used in other parts of the application using the "require()" function.
Example: myFirstModule.js
function greetWithPersonName(name) { console.log ( `Hello ${name}! `); //Here we have used the tilde operator } module.exports = greetWithPersonName; |
1.2) What are Predefined Modules/ Built-in Modules/ Core Modules?
Definition: Predefined modules are provided by Node.js itself and are available for use without the need for installation. These modules are part of the Node.js runtime environment and provide various functionalities for common tasks such as file system operations, networking, HTTP, and more.
Example: usePreDefMod.js
// We are going to use a file system module to manage the file
const fs = require ('fs'); fs.readFile ('text.txt, 'utf8', (err, data) => { if (err) { console.error (err); return; } console.log (data); }); |
No comments:
Post a Comment