- Home
-
HTML
HTML Introduction HTML Tags HTML Elements HTML Attributes HTML Heading HTML Paragraph HTML Formatting HTML Quotations HTML Comments HTML Styles HTML Color HTML CSS HTML Images HTML Favicon HTML Links HTML DIV HTML Tables HTML Table Size HTML Table Head Table Padding & Spacing Table colspan rowspsn HTML Table Styling HTML Colgroup HTML List HTML Block & Inline HTML Classes HTML Id HTML Iframes HTML Head HTML Layout HTML Semantic Elements HTML Style Guide HTML Forms HTML Form Attribute HTML Form Element HTML input type HTML Computer code HTML Entity HTML Symbol HTML Emojis HTML Charset HTML Input Form Attribute HTML URL Encoding
-
CSS
CSS Introduction CSS Syntax CSS Selector How To Add CSS CSS Comments CSS Colors CSS Background color CSS background-image CSS Borders CSS Margins CSS Height, Width and Max-width CSS Box Model CSS Outline CSS Text CSS Fonts CSS Icon CSS Links CSS Tables CSS Display CSS Maximum Width CSS Position z-index Property
- JavaScript
-
JQuery
What is jQuery? Benefits of using jQuery Include jQuery Selectors. Methods. The $ symbol and shorthand. Selecting elements Getting and setting content Adding and removing elements Modifying CSS and classes Binding and Unbinding events Common events: click, hover, focus, blur, etc Event delegation Using .on() for dynamic content Showing and hiding elements Fading elements in and out Sliding elements up and down .animate() Understanding AJAX .ajax() .load(), .get(), .post() Handling responses and errors. Parent Chlid Siblings Filtering Elements Using find Selecting form elements Getting form values Setting form values Form validation Handling form submissions jQuery plugins Sliders plugins $.each() $.trim() $.extend() Data attributes Debugging jQuery code
-
Bootstrap 4
What is Bootstrap Benefits of using Setting up Container Row and Column Grid Classes Breakpoints Offsetting Columns Column Ordering Basic Typography Text Alignment Text colors Backgrounds Display Font Size Utilities Buttons Navs and Navbar Forms Cards Alerts Badges Progress Bars Margin Padding Sizing Flexbox Dropdowns Modals Tooltips Popovers Collapse Carousel Images Tables Jumbotron Media Object
- Git
-
PHP
PHP Introduction PHP Installation PHP Syntax PHP Comments PHP Variable PHP Echo PHP Data Types PHP Strings PHP Constant PHP Maths PHP Number PHP Operators PHP if else & if else if PHP Switch PHP Loops PHP Functions PHP Array PHP OOps PHP Class & Object PHP Constructor PHP Destructor PHP Access Modfiers PHP Inheritance PHP Final Keyword PHP Class Constant PHP Abstract Class PHP Superglobals PHP Regular Expression PHP Interfaces PHP Static Method PHP Static Properties PHP Namespace PHP Iterable PHP Form Introduction PHP Form Validation PHP Complete Form PHP Date and Time PHP Include Files PHP - Files & I/O File Upload PHP Cookies PHP SESSION PHP Filters PHP Callback Functions PHP JSON PHP AND Exceptions PHP Connect database
-
MY SQL
SQL Introduction Syntax Select statement Select Distinct WHERE Clause Order By SQL AND Operator SQL OR Operator SQL NOT Operator SQL LIKE SQL IN SQL BETWEEN SQL INSERT INTO SQL NULL Values SQL UPDATE SQL DELETE SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause SQL MIN() and MAX() Functions SQL COUNT() Function SQL SUM() SQL AVG() SQL Aliases SQL JOIN SQL INNER JOIN SQL LEFT JOIN SQL RIGHT JOIN SQL FULL OUTER JOIN SQL Self Join SQL UNION SQL GROUP BY SQL HAVING SQL EXISTS SQL ANY and ALL SQL SELECT INTO SQL INSERT INTO SELECT SQL CASE SQL NULL Functions SQL Stored Procedures SQL Comments SQL Operators SQL CREATE DATABASE SQL DROP DATABASE SQL BACKUP DATABASE SQL CREATE TABLE SQL DROP TABLE SQL ALTER TABLE SQL Constraints SQL NOT NULL SQL UNIQUE Constraint SQL PRIMARY KEY SQL FOREIGN KEY SQL CHECK Constraint SQL CREATE INDEX SQL AUTO INCREMENT SQL Dates SQL Views SQL Injection SQL Hosting SQL Data Types
Creating custom modules in node js
Creating custom modules in Node.js allows you to organize your code into reusable chunks. This is especially useful for maintaining large codebases. Here’s a step-by-step guide on how to create and use custom modules in Node.js, along with examples.
1. Creating a Basic Custom Module
Let's start by creating a simple custom module.
Step 1: Create a new JavaScript file for your module.
Create a file called myModule.js
.
// myModule.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
Here, we defined a function greet
that takes a name as an argument and returns a greeting string. We then use module.exports
to export this function so it can be used in other files.
Step 2: Import and use the custom module in another file.
Create another file called app.js
.
// app.js
const greet = require('./myModule');
const greeting = greet('John');
console.log(greeting); // Output: Hello, John!
Here, we use require('./myModule')
to import the greet
function from myModule.js
and use it in app.js
.
2. Creating a Module with Multiple Exports
Sometimes, you might want to export multiple functions or objects from a module.
Step 1: Define multiple exports.
Update myModule.js
to include multiple functions.
// myModule.js
function greet(name) {
return `Hello, ${name}!`;
}
function farewell(name) {
return `Goodbye, ${name}!`;
}
module.exports = {
greet,
farewell
};
Now, myModule.js
exports both the greet
and farewell
functions as an object.
Step 2: Import and use the functions in another file.
Update app.js
to use both functions.
// app.js
const myModule = require('./myModule');
const greeting = myModule.greet('John');
const farewellMessage = myModule.farewell('John');
console.log(greeting); // Output: Hello, John!
console.log(farewellMessage); // Output: Goodbye, John!
Here, we destructure the myModule
object to access both the greet
and farewell
functions.
3. Organizing Code with Submodules
You can organize your code further by having submodules within a module.
Step 1: Create a directory structure.
Create a directory called utils
, and inside it, create two files: greet.js
and farewell.js
.
// utils/greet.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
// utils/farewell.js
function farewell(name) {
return `Goodbye, ${name}!`;
}
module.exports = farewell;
Step 2: Create an index file to bundle the submodules.
Create an index.js
file inside the utils
directory.
// utils/index.js
const greet = require('./greet');
const farewell = require('./farewell');
module.exports = {
greet,
farewell
};
This index.js
file acts as an entry point that bundles all submodules.
Step 3: Import and use the submodules.
Update app.js
to use the utils
module.
// app.js
const utils = require('./utils');
const greeting = utils.greet('John');
const farewellMessage = utils.farewell('John');
console.log(greeting); // Output: Hello, John!
console.log(farewellMessage); // Output: Goodbye, John!
4. Creating and Using Classes in Modules
You can also export classes from your modules.
Step 1: Define a class in the module.
Create a file called Person.js
.
// Person.js
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
farewell() {
return `Goodbye, ${this.name}!`;
}
}
module.exports = Person;
Here, we defined a Person
class with greet
and farewell
methods.
Step 2: Import and use the class in another file.
Update app.js
to use the Person
class.
// app.js
const Person = require('./Person');
const john = new Person('John');
console.log(john.greet()); // Output: Hello, John!
console.log(john.farewell()); // Output: Goodbye, John!
5. Handling Asynchronous Code in Modules
Modules can also export functions that deal with asynchronous operations.
Step 1: Create a module with an asynchronous function.
Create a file called fetchData.js
.
npm install node-fetch
// fetchData.js
const fetch = require('node-fetch');
async function fetchData(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
module.exports = fetchData;
Here, we use async/await
to handle an asynchronous operation, like fetching data from an API.
Step 2: Import and use the asynchronous function.
Update app.js
to use the fetchData
function.
// app.js
const fetchData = require('./fetchData');
async function main() {
const data = await fetchData('https://jsonplaceholder.typicode.com/posts/1');
console.log(data);
}
main();
This code fetches data from a JSON API and logs it to the console.
Summary
Custom modules in Node.js allow you to write modular, reusable code. Whether you're exporting simple functions, multiple values, classes, or even handling asynchronous operations, Node.js provides a flexible system for organizing your code.
Would you like to explore any specific aspect of custom modules in more detail?
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2024 © All rights reserved.