Tuesday, 8 July 2025

Node.js Basic to Advance

Node.js Basic to Advance Blog

Node.js Tutorial: From Basic to Advance

Everything you need to become a Node.js Developer

🚀 Introduction to Node.js

Node.js is an open-source, cross-platform JavaScript runtime environment that allows you to run JavaScript code outside a web browser. It's widely used for building scalable network applications.

⚙️ Installation & Setup

Download Node.js from nodejs.org. Use the terminal/command prompt to check installation:

node -v
npm -v

📦 Node.js Core Modules

  • fs – File system operations
  • http – Create HTTP servers
  • https – HTTPS servers with SSL/TLS
  • path – Handle and transform file paths
  • url – Parse and format URLs
  • querystring – Parse and stringify URL query strings
  • events – Event-driven programming with EventEmitter
  • stream – Streaming data processing (read/write)
  • os – Operating system-related utility methods
  • crypto – Cryptographic operations (hashing, encryption)
  • zlib – Compression and decompression (gzip, deflate)
  • util – Utility functions (promisify, inherits, etc.)
  • timers – Scheduling functions like setTimeout, setInterval
  • dns – DNS lookup and hostname resolution
  • net – Low-level networking (TCP/IPC)
  • child_process – Spawn and manage child processes
  • process – Provides info and control over the current Node process
  • readline – Read data from readable streams line by line
  • buffer – Handling binary data
  • console – Console logging functions (console.log, etc.)
  • v8 – Interact with the V8 engine internals
  • assert – Assertion testing for validating invariants
  • cluster – Run multiple instances of Node.js for load balancing
  • tty – Support for terminal I/O (used in REPL)
  • repl – Read-Eval-Print Loop for interactive console
  • module – Internal module loader (advanced use)

📁 Recommended Project Structure

project/
├── node_modules/
├── public/
├── src/
│   ├── controllers/
│   ├── models/
│   ├── routes/
│   ├── middlewares/
│   └── utils/
├── .env
├── package.json
└── server.js

This structure helps keep the code organized and scalable.

🌐 Express.js Framework

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.listen(3000);

🧩 Middleware in Node.js

Middleware functions are functions that have access to the request object, the response object, and the next middleware function in the application’s request-response cycle.

🔐 Authentication & Authorization

Authentication can be handled using libraries like passport.js or jsonwebtoken (JWT). Implement secure routes and protect sensitive data.

📁 File Uploads in Node.js

Use libraries like multer to handle file uploads. It helps parse multipart/form-data requests.

📡 Real-Time Communication with Socket.io

Build real-time features like chat apps using socket.io that leverages WebSockets.

🗄️ Using Databases (MySQL, MongoDB)

Connect Node.js to databases using:

  • MongoDB: via Mongoose
  • MySQL: via mysql2 or sequelize ORM

💡 Best Practices

  • Use environment variables with dotenv
  • Validate input with Joi or zod
  • Use try-catch with async/await
  • Follow proper folder structure
  • Write unit tests using Jest or Mocha

❓ Node.js Interview Questions (Basic to Advanced)

  • What is Node.js and how does it work?
  • Explain the event-driven architecture of Node.js.
  • What is the difference between synchronous and asynchronous programming?
  • What are Node.js core modules? Name a few.
  • How does the event loop work in Node.js?
  • What is npm and what is it used for?
  • How do you create a simple HTTP server in Node.js?
  • What is Express.js and why is it used?
  • Explain middleware in Express.js.
  • How do you handle file uploads in Node.js?
  • What is a callback function and how is it used in Node?
  • What is the purpose of `require()` in Node.js?
  • How can you connect Node.js to a MongoDB or MySQL database?
  • Explain error handling in Node.js.
  • What is JWT and how is it used in authentication?
  • What is the difference between `process.nextTick()`, `setImmediate()`, and `setTimeout()`?
  • How does clustering work in Node.js?
  • How would you secure a Node.js application?
  • What are Streams in Node.js?
  • How does real-time communication work with Socket.io?

🍃 MongoDB Interview Questions (Basic to Advanced)

  • What is MongoDB and how is it different from SQL databases?
  • What are Documents and Collections in MongoDB?
  • What is BSON?
  • How do you create a database and collection in MongoDB?
  • Explain CRUD operations in MongoDB with examples.
  • What is the _id field in MongoDB?
  • How do indexes work in MongoDB?
  • What is aggregation in MongoDB?
  • Difference between $match, $group, and $project in aggregation pipeline?
  • What are embedded documents and when to use them?
  • How do you perform joins in MongoDB?
  • What is a replica set?
  • What is sharding and why is it used?
  • Difference between find() and findOne()
  • How do you perform pagination in MongoDB?
  • What are schema validations in MongoDB?
  • Explain the role of MongoDB Atlas.
  • How do you secure MongoDB in production?
  • What is the difference between MongoDB and Mongoose?
  • What are transactions in MongoDB and how are they used?

🚀 Express.js Interview Questions

  • What is Express.js and why is it used?
  • How do you install and set up Express?
  • What are the main features of Express.js?
  • What is middleware in Express.js?
  • Difference between application-level and router-level middleware?
  • How do you define routes in Express?
  • How do you handle 404 and error middleware in Express?
  • What are the different HTTP methods supported by Express?
  • How do you parse incoming request bodies?
  • How can you handle file uploads in Express?
  • How to connect a MongoDB/Mongoose model in Express?
  • What is the use of `express.static()`?
  • How to handle route parameters and query strings?
  • What is `req` and `res` in Express?
  • How do you implement JWT authentication in Express?
  • How to structure a large Express application?
  • What are CORS and how do you enable them in Express?
  • How do you protect routes in Express?
  • How can you create and use routers in Express?
  • Difference between `app.use()` and `app.get()`?

🧠 Node.js Advanced Interview Questions (5+ Years Experience)

  • Explain the Node.js event loop in detail. How does it handle async I/O?
  • How does Node.js achieve non-blocking I/O using libuv?
  • What are the performance bottlenecks in a Node.js application and how do you resolve them?
  • How would you scale a Node.js application across multiple CPU cores?
  • What is clustering in Node.js and when should you use it?
  • How do you handle memory leaks in Node.js?
  • How would you implement caching in a high-traffic Node.js API?
  • What are Streams in Node.js and how do they improve performance?
  • How do you secure a Node.js REST API in production?
  • What are worker threads and when should you use them over clustering?
  • Explain the difference between process.nextTick(), setImmediate(), and setTimeout().
  • How would you implement rate limiting in a Node.js application?
  • What’s the difference between synchronous and asynchronous error handling in Node.js?
  • How do you implement logging in a production Node.js app?
  • What is load balancing and how can it be used with Node.js apps?
  • Explain the architecture of your last enterprise-level Node.js project.
  • What tools do you use for profiling and monitoring Node.js apps in production?
  • How do you ensure graceful shutdown in a Node.js app?
  • How does garbage collection work in Node.js?
  • What are some anti-patterns in Node.js and how do you avoid them?

✅ Conclusion

Node.js is powerful for building backend services, APIs, real-time applications, and even automation scripts. Continue exploring modules, tools, and best practices to become a full-stack Node.js developer.

© 2025 NodeJS Learning Blog | Built with ❤️ and Tailwind CSS

Monday, 7 July 2025

Important links for developer

Developer Tools & Resources

🌐 Developer Tools & Resources 🌐

🌐 General Developer Resources

GitHub

Version control & collaboration

Stack Overflow

Developer Q&A forum

MDN Web Docs

HTML, CSS, JS documentation

Can I use

Browser compatibility tables

FreeCodeCamp

Free coding tutorials

DevDocs

Concise API & language docs

JSON Formatter

Format & validate JSON

Postman

API testing & collaboration

CodePen

Frontend playground

JSFiddle

Online code sandbox

💻 Backend Development

Laravel

Official Laravel documentation

Node.js

Node.js documentation

Express.js

Minimalist Node.js framework docs

PHP Manual

PHP language reference

MySQL Docs

MySQL database reference

🎨 Frontend Development

Tailwind CSS

Utility-first CSS framework

Bootstrap

Responsive CSS framework

ReactJS

React official documentation

Angular

Google's frontend framework

Vue.js

Progressive JS framework

Figma

Collaborative UI/UX design tool

⚙️ DevOps & Deployment

Docker

Containerization platform

Kubernetes

Container orchestration

GitHub Actions

CI/CD from GitHub

Netlify

Frontend hosting & deployment

Vercel

Next.js hosting & CI/CD

🔐 Security Tools

OWASP Top 10

Web security risks list

Have I Been Pwned

Check email breach history

JWT.io

Decode & debug JSON Web Tokens

🛠️ Code Editors & IDEs

VS Code

Lightweight code editor from Microsoft

Sublime Text

Minimal & fast editor

Atom

Hackable editor (archived)

Notepad++

Simple Windows code editor

IntelliJ IDEA

Popular Java IDE

PyCharm

Python IDE with Django support

🤖 AI-Powered Tools

Cursor AI

AI-powered developer editor

Tabnine

AI assistant for coding

Codeium

Free AI autocomplete

GitHub Copilot

AI pair programmer

Trae AI

Smart AI for dev workflows

🔧 Developer Utilities

Docker Desktop

Run containers locally

Git

Version control system

Node.js

JavaScript runtime

MongoDB Compass

Visual MongoDB client

MySQL Workbench

Database modeling & queries

📦 Package Managers

NPM

Node.js package manager

Packagist

Composer packages for PHP

Yarn

Fast JavaScript package manager

🧩 Technologies

JavaScript

Dynamic scripting language for web development

TypeScript

Typed superset of JavaScript

Python

Versatile language for backend, data, and automation

PHP

Server-side scripting language for web apps

Ruby

Simple, elegant scripting language

Go (Golang)

Fast, statically typed compiled language

Java

Robust OOP language used in enterprise apps

.NET

Microsoft’s framework for C#, F#, and more

React

UI library for building user interfaces

Next.js

React-based framework for SSR and SSG

Vue.js

Progressive JavaScript framework

Angular

Google's full-featured frontend framework

Node.js

JS runtime for server-side development

Express.js

Minimal backend framework for Node.js

Laravel

Modern PHP framework with elegant syntax

Spring

Powerful Java framework for backend systems

Thursday, 11 July 2024

Push notiifcation on web

To ensure that push notifications and focus state detection work correctly across all browsers, including Safari, you need to consider browser-specific limitations and features. Safari has some unique requirements for handling push notifications and visibility changes.

Steps to Handle Push Notifications and Page Visibility in Safari:

  1. Use the Page Visibility API for Detecting Page Visibility:
    • This API works in most modern browsers, including Safari.
  2. Handle Notifications:
    • Use the Notification API to handle notifications when the page is not in focus.
  3. Consider Browser-specific Features:
    • Ensure that the Firebase setup is compatible with all browsers, including Safari.
    • For Safari, ensure that notifications are enabled in the Safari settings.

Updated Implementation:

1. Firebase Configuration and Message Handling in Web App:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Firebase Push Notifications</title>
    <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <script>
        // Your web app's Firebase configuration
        var firebaseConfig = {
            apiKey: "YOUR_API_KEY",
            authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
            projectId: "YOUR_PROJECT_ID",
            storageBucket: "YOUR_PROJECT_ID.appspot.com",
            messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
            appId: "YOUR_APP_ID"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);

        // Initialize Firebase Cloud Messaging
        const messaging = firebase.messaging();

        // Request permission and get token
        $(document).ready(function() {
            messaging.getToken({ vapidKey: 'YOUR_PUBLIC_VAPID_KEY' })
                .then((currentToken) => {
                    if (currentToken) {
                        console.log('FCM Token:', currentToken);
                        // Send the token to the server
                        $.post('save_token.php', { token: currentToken }, function(response) {
                            console.log(response);
                        });
                    } else {
                        console.log('No registration token available. Request permission to generate one.');
                    }
                })
                .catch((err) => {
                    console.error('An error occurred while retrieving token. ', err);
                });

            // Handle incoming messages
            messaging.onMessage((payload) => {
                console.log('Message received. ', payload);

                if (document.visibilityState === 'visible') {
                    // Handle the message when the page is in focus
                    console.log('Foreground message:', payload);
                } else {
                    // Show notification when the page is not in focus
                    new Notification(payload.notification.title, {
                        body: payload.notification.body,
                        icon: payload.notification.icon
                    });
                }
            });
        });

        // Request notification permission
        function requestNotificationPermission() {
            Notification.requestPermission().then(function(permission) {
                if (permission === 'granted') {
                    console.log('Notification permission granted.');
                } else {
                    console.log('Unable to get permission to notify.');
                }
            });
        }

        // Check the visibility state of the page
        document.addEventListener('visibilitychange', function() {
            if (document.visibilityState === 'visible') {
                console.log('Page is in focus.');
            } else {
                console.log('Page is not in focus.');
            }
        });

        // Call the requestNotificationPermission function to request permissions
        requestNotificationPermission();
    </script>
</body>
</html>

#############################################################################

To set up a web push notification permission request in Safari with a jQuery alert button for a Laravel framework project, follow these steps:

Create the Alert Button in HTML: Add an alert button to your view file (usually a Blade template in Laravel).

html
<!-- resources/views/your_view.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Push Notification</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <button id="alertButton">Enable Notifications</button>

    <script>
        // Add your jQuery and Safari push notification request code here
    </script>
</body>
</html>

Add jQuery and Safari Push Notification Request Code: Include the necessary jQuery code to handle the button click event and request push notification permission.
<script>
$(document).ready(function() {
    $('#alertButton').click(function() {
        // Check if the browser supports notifications
        if (window.safari && window.safari.pushNotification) {
            var permissionData = window.safari.pushNotification.permission('web.com.example.domain'); // Use your own web push ID here

            checkRemotePermission(permissionData);
        } else {
            alert('This browser does not support push notifications.');
        }
    });

    function checkRemotePermission(permissionData) {
        if (permissionData.permission === 'default') {
            // The user hasn't been asked yet or the user has dismissed the request
            window.safari.pushNotification.requestPermission(
                'https://example.com', // The web service URL
                'web.com.example.domain', // Your web push ID
                {}, // Data to send with the request (optional)
                checkRemotePermission // The callback function to call with the response
            );
        } else if (permissionData.permission === 'denied') {
            alert('Push notifications are denied.');
        } else if (permissionData.permission === 'granted') {
            alert('Push notifications are granted.');
        }
    }
});
</script>

Set Up Your Safari Web Push ID and Web Service URL: Ensure that you have registered your website and obtained a web push ID from Apple. Replace web.com.example.domain with your actual web push ID and https://example.com with your actual web service URL.

Configure Laravel Routes and Controller: Set up the necessary routes and controller methods in Laravel to handle any server-side logic related to push notifications

// routes/web.php
Route::get('/push', 'PushController@requestPermission');

// app/Http/Controllers/PushController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PushController extends Controller
{
    public function requestPermission(Request $request)
    {
        // Handle the push notification permission request logic here
        // For now, simply return a response
        return response()->json(['status' => 'Permission requested']);
    }
}

By following these steps, you will have a jQuery alert button in your Laravel application that requests permission for web push notifications in Safari. Ensure you replace placeholders with actual values specific to your application and push notification service.



Wednesday, 19 June 2024

Check if the caption length exceeds 200 characters and add a scroll if needed

// Check if the caption length exceeds 200 characters and add a scroll if needed


        if (imageFileCaption.length > 200) {
            $('#imageMessageCaption').addClass('scrollable-file-caption');
        } else {
            $('#imageMessageCaption').removeClass('scrollable-file-caption');
        }

Explanation

  1. CSS: The .scrollable-caption class limits the maximum height of the element and adds a vertical scroll if the content overflows.
  2. JavaScript: The code checks if the length of the caption exceeds 200 characters. If it does, it adds the .scrollable-caption class to #imageMessageCaption. If the caption is 200 characters or fewer, it ensures the class is removed to avoid unnecessary scrolling.

This approach ensures that only long captions get a vertical scroll, while shorter captions are displayed normally. Adjust the max-height in the CSS according to your design requirements.

 

Friday, 29 September 2023

To search for an element in a JavaScript array based on a username

To search for an element in a JavaScript array based on a username, you can use the `Array.prototype.find()` method. This method will iterate through the array and return the first element that matches the provided condition. Here's how you can do it:

Suppose you have an array of user objects like this:

```javascript
const users = [
  { username: "user1", name: "John" },
  { username: "user2", name: "Jane" },
  { username: "user3", name: "Bob" },
  // ... other user objects
];
```

You can search for a user by their username using `Array.prototype.find()` like this:

```javascript
const usernameToSearch = "user2"; // Change this to the username you want to search for

const foundUser = users.find(user => user.username === usernameToSearch);

if (foundUser) {
  console.log("User found:", foundUser.name);
} else {
  console.log("User not found");
}
```

In this example, `Array.prototype.find()` iterates through the `users` array and checks if the `username` property of each user object matches the `usernameToSearch` value. If a match is found, `foundUser` will hold the user object with the matching username. If no match is found, `foundUser` will be `undefined`.

Adjust `usernameToSearch` to the username you want to search for, and the code will find the corresponding user object or indicate if the user is not found.

*************************************************************************

To search for the object in your JSON data based on the `trashed_user.name` property in JavaScript, you can use the `Array.prototype.find()` method just like in the previous example. However, since your data appears to be a single object rather than an array, you don't need to iterate over an array. Instead, you can directly access the `trashed_user.name` property. Here's how you can do it:

```javascript
const jsonData = {
  "id": 1  "created_at": "2023-07-17T09:38:10.000000Z",
  "trashed_user": {
    "id": 1,
    "name": "Jayesh Patel",
  }
};

const nameToSearch = "Jayesh Patel"; // Change this to the name you want to search for

if (jsonData.trashed_user.name === nameToSearch) {
  console.log("Object found:", jsonData);
} else {
  console.log("Object not found");
}
```

In this code, we directly access the `trashed_user.name` property of the `jsonData` object and compare it to the `nameToSearch`. If there is a match, it will log the entire object. If there is no match, it will indicate that the object was not found. Adjust `nameToSearch` to the name you want to search for.


*************************************************************************

If you want to search for an object in an array case-insensitively (meaning it should match both small and capital letters), you can convert both the search string and the data to a consistent case (e.g., lowercase) before performing the search. Here's how you can do that:

```javascript
const jsonData = {
  "id": 1  "created_at": "2023-07-17T09:38:10.000000Z",
  "trashed_user": {
    "id": 1,
    "name": "Jayesh Patel",
  }
};

const nameToSearch = "Jayesh patel"; // Change this to the name you want to search for

const foundObject = jsonArray.find(item => item.trashed_user.name.toLowerCase() === nameToSearch.toLowerCase());

if (foundObject) {
  console.log("Object found:", foundObject);
} else {
  console.log("Object not found");
}
```

In this code, both the `nameToSearch` and the `trashed_user.name` properties are converted to lowercase using `.toLowerCase()` before comparison. This allows for a case-insensitive search, so it will match regardless of the letter casing in the search string and the data. 

************************************************************************


If you want to perform a "like" search, meaning you want to find objects in the array where the `trashed_user.name` property contains a specific substring, you can use the `Array.prototype.filter()` method to filter the array based on a custom condition. Here's how you can do it:

```javascript
const jsonArray = [
  {
    "id": 1,
    "created_at": "2023-07-17T09:38:10.000000Z",
    "trashed_user": {
      "id": 1,
      "name": "Admin Testing",
      "user_role": 0
    }
  },
  // ... other objects in the array
];

const searchTerm = "Testing"; // Change this to the substring you want to search for

const filteredObjects = jsonArray.filter(item => item.trashed_user.name.toLowerCase().includes(searchTerm.toLowerCase()));

if (filteredObjects.length > 0) {
  console.log("Matching objects found:", filteredObjects);
} else {
  console.log("No matching objects found");
}
```

In this code, we use the `Array.prototype.filter()` method to filter the `jsonArray` based on whether the `trashed_user.name` property contains the specified `searchTerm`. Both the `trashed_user.name` and `searchTerm` are converted to lowercase using `.toLowerCase()` for a case-insensitive search. The `filteredObjects` array will contain all objects that match the search criteria, and you can access and manipulate them as needed.

*********************************************************************


If you want to search for all records in an array that are related to "ankita," not just a single record, you can modify the code to use the `Array.prototype.filter()` method to filter multiple matching records. Here's how you can do it:

```javascript
const jsonArray = [
  {
    "id": 1,
    "created_at": "2023-07-17T09:38:10.000000Z",
    "trashed_user": {
      "id": 2,
      "name": "Rakesh Patel",
      "user_role": 0
    }
  },
  {
    "id": 2,
    "created_at": "2023-07-17T09:38:10.000000Z",
    "trashed_user": {
      "id": 265,
      "name": "Ramesh Patel",
        "user_role": 0
    }
  },
  // ... other objects in the array
];

const searchTerm = "Patel"; // Change this to the substring you want to search for

const filteredObjects = jsonArray.filter(item => item.trashed_user.name.toLowerCase().includes(searchTerm.toLowerCase()));

if (filteredObjects.length > 0) {
  console.log("Matching objects found:", filteredObjects);
} else {
  console.log("No matching objects found");
}
```

This code will filter all records in the `jsonArray` where the `trashed_user.name` property contains the specified `searchTerm`. It stores all matching records in the `filteredObjects` array, and you can access and manipulate them as needed.

Monday, 25 September 2023

How to Use HTML5 File Drag and Drop

HTML Drag and Drop interfaces enable web applications to drag and drop files on a web page. This document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page.

Why Need Drag and Drop File Upload Feature?
We always want to have a better user experience on the website. Giving the drag and drop file uploader is convenient for users. A lot of popular websites like Facebook and WordPress are already using this technique.

This feature looks better compared to the traditional way of file uploading. It also improves the user experience as the user simply drags the file and it gets uploaded asynchronously.

Our file uploader will have both options. One can upload the file either using drag and drop or through the file input.

    
 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Drag-and-Drop Media Upload</title>
        <style>
            /* Style the drop zone */
            #file-drop-zone {
                width: 300px;
                height: 150px;
                border: 2px dashed #ccc;
                text-align: center;
                padding: 20px;
                margin: 20px auto;
            }
        </style>
    </head>
    <body>
        <div id="file-drop-zone" ondrop="drop(event)" ondragover="allowDrop(event)">
            Drop media files here.
        </div>

        <script>
            function allowDrop(event) {
                event.preventDefault();
                // Add a visual indication that it's a valid drop target (e.g., change border color)
                event.target.style.border = '2px dashed #007bff';
            }

            function drop(event) {
                event.preventDefault();
                event.target.style.border = '2px dashed #ccc'; // Reset the border color

                const files = event.dataTransfer.files;
                const fileDisplay = document.createElement('ul');

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const listItem = document.createElement('li');
                    listItem.textContent = `${file.name} (${formatBytes(file.size)})`;
                    fileDisplay.appendChild(listItem);
                }

                document.body.appendChild(fileDisplay);
            }

            // Function to format file size in a human-readable format
            function formatBytes(bytes, decimals = 2) {
                if (bytes === 0) return '0 Bytes';

                const k = 1024;
                const dm = decimals < 0 ? 0 : decimals;
                const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

                const i = Math.floor(Math.log(bytes) / Math.log(k));

                return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
            }
        </script>
    </body>
    </html>
 

        In this code:

  1. The HTML file contains a file-drop-zone div element where you can drag and drop files.
  2. The allowDrop function is called when a file is dragged over the drop zone, preventing the default behavior and adding a visual indication that it's a valid drop target.
  3. The drop function handles the dropped files. It displays the names and sizes of the dropped files in an unordered list.
  4. There's also a formatBytes function to format file sizes in a human-readable format.
  5. Remember that this is a simple example. In a real application, you would typically send the uploaded files to a server for storage and implement error handling and security measures.


Node.js Basic to Advance

Node.js Basic to Advance Blog Node.js Tutorial: From Basic to Advance Everything you need to become a...