Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Node.js Hosting - HostForLIFE :: What is the Event Loop in Node.js, and How Does It Work?

clock August 14, 2025 07:41 by author Peter

The Event Loop is the secret of Node.js's ability to manage thousands of concurrent actions despite being single-threaded, as developers often learn. Even with a single main thread, this approach makes sure Node.js runs code effectively without interfering with other processes.

The Reason for the Event Loop
JavaScript was created to manage keystrokes and clicks on interactive web sites when they ran in browsers.  The event loop in a browser guarantees fluid interactions without causing the user interface to freeze. JavaScript was brought to the server side by Node.js, where it handles I/O tasks including sending network requests, reading files, and querying databases.  These can be managed without halting the execution of other code thanks to the Event Loop.

How the Event Loop Works in Node.js
The Event Loop is managed by libuv, a C library that provides asynchronous I/O. Here’s the step-by-step process:

  • Call Stack Execution: Node.js runs your synchronous code first.
  • Delegating Tasks: When asynchronous functions like setTimeout or fs.readFile are called, they are handed over to background APIs or the thread pool.
  • Callback Queue: Once the background task is done, its callback is added to the queue.
  • Event Loop Processing: The event loop checks if the call stack is empty and then pushes the next callback from the queue to be executed.

Event Loop Phases
The Node.js Event Loop runs in phases:

  • Timers: Executes callbacks from setTimeout and setInterval.
  • Pending Callbacks: Executes callbacks for system operations.
  • Idle, Prepare: Internal use only.
  • Poll: Retrieves new I/O events; executes I/O callbacks.
  • Check: Executes setImmediate callbacks.
  • Close Callbacks: Executes close events (e.g., socket.on('close')).


Microtasks (like process.nextTick() and resolved promises) run between these phases, before moving to the next phase.

Example: Event Loop in Action
Example:
console.log("Start");

setTimeout(() => {
  console.log("Timeout callback");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise callback");
});

console.log("End");


Output:

  • Start
  • End
  • Promise callback
  • Timeout callback

Explanation:
Promise callback runs before Timeout callback because promises are microtasks, which have higher priority than macrotasks like setTimeout.

Understanding Microtasks vs. Macrotasks
Microtasks: process.nextTick(), Promise.then(). Run immediately after the current operation.
Macrotasks: setTimeout(), setImmediate(), I/O callbacks. Run in the normal event loop phases.

Key Points to Remember
Node.js is single-threaded for JavaScript execution.
The Event Loop allows asynchronous, non-blocking operations.
Microtasks always run before the next macrotask.
libuv handles background tasks and the thread pool.

Summary
The Event Loop is the heart of Node.js's asynchronous programming model. It ensures that even though JavaScript runs on a single thread, Node.js can handle thousands of concurrent tasks without blocking. By delegating I/O operations to the background and using a queue system for callbacks, it keeps applications fast and responsive. Understanding the Event Loop is essential for writing efficient Node.js applications.



Node.js Hosting - HostForLIFE :: Uploading Files from React to Cloudinary: A Comprehensive Guide with Secure Backend, Progress, and Preview (2025)

clock July 28, 2025 07:24 by author Peter

A common feature of many contemporary web applications is the ability to upload files, such as documents, videos, and images. In this tutorial, we'll demonstrate how to use Cloudinary, a potent media management platform, to create a robust file upload feature in a React (v18+) application. We'll also go over secure backend-signed uploads using Node.js (Express). Using functional components, React Hooks, and contemporary best practices, we'll create a reusable upload component that supports a variety of file types, displays a preview when feasible, tracks the upload process, and securely uploads media using a backend-generated signature.

What is Cloudinary?
Cloudinary is a cloud-based service for storing, optimizing, and delivering images, videos, and other media files. It simplifies media handling by providing:

  • Media upload and storage
  • CDN delivery and transformation
  • Automatic optimization and responsive images
  • Support for multiple media types

What Will We Build?
A full-stack app (React + Node.js) that:

  • Accepts images, videos, and documents as input
  • Shows previews for image/video types
  • Tracks upload progress
  • Generates a secure upload signature on the backend
  • Uploads securely to Cloudinary

Project Structure

 

cloudinary-react-upload/
├── client/            # React frontend
│   ├── src/
│   │   ├── components/FileUploader.jsx
│   │   ├── App.jsx
│   │   └── main.jsx
│   └── .env
├── server/            # Node.js backend
│   ├── index.js
│   └── .env
├── package.json (root - manages both client/server via scripts)

 

Step 1. Cloudinary Setup

  • Sign up at cloudinary.com
  • Go to your dashboard and note:
    • Cloud Name
    • API Key
    • API Secret
  • Navigate to Settings > Upload > Upload Presets
    • Create a new signed preset
    • Enable "Auto format" and "Auto resource type"

Backend .env (in server/.env)
CLOUD_NAME=your_cloud_name
CLOUD_API_KEY=your_api_key
CLOUD_API_SECRET=your_api_secret
UPLOAD_PRESET=your_signed_preset

Step 2: Backend Setup with Node.js (Express)
Install dependencies
cd server
npm init -y
npm install express dotenv cors cloudinary

server/index.js
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { v2 as cloudinary } from 'cloudinary';

dotenv.config();
const app = express();
app.use(cors());

cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.CLOUD_API_KEY,
  api_secret: process.env.CLOUD_API_SECRET
});

app.get('/get-signature', (req, res) => {
  const timestamp = Math.floor(Date.now() / 1000);
  const signature = cloudinary.utils.api_sign_request(
    {
      timestamp,
      upload_preset: process.env.UPLOAD_PRESET,
    },
    process.env.CLOUD_API_SECRET
  );

  res.json({
    timestamp,
    signature,
    cloudName: process.env.CLOUD_NAME,
    apiKey: process.env.CLOUD_API_KEY,
    uploadPreset: process.env.UPLOAD_PRESET,
  });
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));


Run the backend:
node index.js

Step 3. React Frontend Setup (Vite)
Create project and install dependencies:
npm create vite@latest client -- --template react
cd client
npm install axios

Frontend .env (in client/.env)
VITE_API_URL=http://localhost:4000

Step 4. FileUploader Component (Secure Upload)

client/src/components/FileUploader.jsx

import { useState, useRef } from 'react';
import axios from 'axios';

const FileUploader = () => {
  const [file, setFile] = useState(null);
  const [previewUrl, setPreviewUrl] = useState(null);
  const [progress, setProgress] = useState(0);
  const [uploadedUrl, setUploadedUrl] = useState(null);
  const inputRef = useRef();

  const handleFileChange = (e) => {
    const selected = e.target.files[0];
    setFile(selected);
    setUploadedUrl(null);
    setProgress(0);

    if (selected?.type.startsWith('image') || selected?.type.startsWith('video')) {
      const url = URL.createObjectURL(selected);
      setPreviewUrl(url);
    } else {
      setPreviewUrl(null);
    }
  };

  const handleUpload = async () => {
    if (!file) return;

    try {
      const { data: signatureData } = await axios.get(`${import.meta.env.VITE_API_URL}/get-signature`);

      const formData = new FormData();
      formData.append('file', file);
      formData.append('api_key', signatureData.apiKey);
      formData.append('timestamp', signatureData.timestamp);
      formData.append('upload_preset', signatureData.uploadPreset);
      formData.append('signature', signatureData.signature);

      const { data } = await axios.post(
        `https://api.cloudinary.com/v1_1/${signatureData.cloudName}/auto/upload`,
        formData,
        {
          onUploadProgress: (e) => {
            const percent = Math.round((e.loaded * 100) / e.total);
            setProgress(percent);
          },
        }
      );

      setUploadedUrl(data.secure_url);
      inputRef.current.value = null;
    } catch (err) {
      console.error('Upload failed:', err);
      alert('Upload failed. Check console.');
    }
  };

  return (
    <section style={{ padding: '1rem' }}>
      <h2>Secure File Upload to Cloudinary</h2>

      <input
        ref={inputRef}
        type="file"
        accept="image/*,video/*,.pdf,.doc,.docx"
        onChange={handleFileChange}
      />

      {previewUrl && file?.type.startsWith('image') && (
        <img src={previewUrl} alt="Preview" width={200} style={{ marginTop: '1rem' }} />
      )}

      {previewUrl && file?.type.startsWith('video') && (
        <video width={300} controls style={{ marginTop: '1rem' }}>
          <source src={previewUrl} type={file.type} />
        </video>
      )}

      {!previewUrl && file && (
        <p style={{ marginTop: '1rem' }}>Selected File: {file.name}</p>
      )}

      <button onClick={handleUpload} disabled={!file} style={{ marginTop: '1rem' }}>
        Upload
      </button>

      {progress > 0 && <p>Progress: {progress}%</p>}

      {uploadedUrl && (
        <div style={{ marginTop: '1rem' }}>
          <p>Uploaded Successfully!</p>
          <a href={uploadedUrl} target="_blank" rel="noopener noreferrer">View File</a>
        </div>
      )}
    </section>
  );
};

export default FileUploader;


Step 5. Use Component in App
client/src/App.jsx

import FileUploader from './components/FileUploader';

function App() {
  return (
    <div style={{ maxWidth: '600px', margin: '0 auto', fontFamily: 'sans-serif' }}>
      <h1>Cloudinary File Uploader</h1>
      <FileUploader />
    </div>
  );
}

export default App;

Why Use Signed Uploads?

Cloudinary offers two ways to upload files:

  • Unsigned Uploads: Anyone with your upload preset can upload files. Not recommended for production because it's insecure.
  • Signed Uploads (used in this guide): The backend signs each upload request using your Cloudinary secret key, making it secure. This ensures:
    • Files are uploaded only by authenticated users (if you add auth)
    • Upload presets can't be abused
    • You have more control over what's uploaded

Best Practices

  • Use /auto/upload endpoint to auto-detect file type (image/video/raw)
  • Don’t expose Cloudinary secret API keys in frontend
  • Limit file size on client and/or backend

Supported File Types
Cloudinary accepts:

  • Images: jpg, png, webp, etc.
  • Videos: mp4, mov, avi
  • Documents: pdf, doc, docx, txt (uploaded as raw)

Conclusion
In this post, we developed a cutting-edge React file uploader that works flawlessly with Cloudinary. It offers a safe, production-ready starting point, preview capabilities, progress tracking, and support for a variety of file types. Blogs, admin panels, profile setups, and CMSs can all make use of this uploader. Take into account backend signed uploads or Cloudinary's transformation capabilities for more complex use cases.



AngularJS Hosting Europe - HostForLIFE :: Angular Subscription Management: Using RxJS to Fix Memory Leaks

clock July 21, 2025 08:26 by author Peter

Angular uses RxJS Observables quite extensively for asynchronous data anything from HTTP requests, form value changes, events, route parameters, and many more. Most of the time, you would subscribe to them, but not unsubscribing properly may cause memory leaks and unexpected behavior, especially in large or long-running apps. In this article, we share how we faced a real-life issue related to missed unsubscriptions, how we identified the leak, and how we applied best practices, such as the takeUntil operator and a reusable base class.

Real Scenario
In various dashboard applications, several components had the possibility of listening to data streams coming from the API, user interactions, and changes in route parameters. Such components use subscription on observables through the RxJS subscribe() method inside the Angular lifecycle hooks of ngOnInit().

Example
ngOnInit(): void {
  this.route.params.subscribe(params => {
    this.loadData(params['id']);
  });

  this.userService.getUser().subscribe(user => {
    this.user = user;
  });
}


After navigating between routes multiple times, we noticed the following issues.

  • Console logs appeared multiple times for the same action.
  • Network requests were duplicated.
  • The browser’s memory usage slowly increased over time.

Root Cause

  • Upon inspection using Chrome DevTools memory tab and Angular DevTools, we found that components were not being garbage collected. This was due to active subscriptions holding references to destroyed components.
  • Solution: Using the takeUntil Pattern with Subject.

To fix this, we implemented the takeUntil pattern with a private Subject.

Step 1. Declare an Unsubscribe Subject.
private destroy$ = new Subject<void>();

Step 2. Use takeUntil(this.destroy$) in Every Subscription.
ngOnInit(): void {
  this.route.params
    .pipe(takeUntil(this.destroy$))
    .subscribe(params => this.loadData(params['id']));

  this.userService.getUser()
    .pipe(takeUntil(this.destroy$))
    .subscribe(user => this.user = user);
}


Step 3. Emit and complete the Subject in ngOnDestroy().
ngOnDestroy(): void {
  this.destroy$.next();
  this.destroy$.complete();
}

This pattern ensures that all subscriptions automatically unsubscribe when the component is destroyed.

Improvement: Create a Base Component Class

To avoid repeating the same code in every component, we created a base class.
export abstract class BaseComponent implements OnDestroy {
  protected destroy$ = new Subject<void>();

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}


Now, in any component.
export class MyComponent extends BaseComponent implements OnInit {

  ngOnInit(): void {
    this.dataService.getData()
      .pipe(takeUntil(this.destroy$))
      .subscribe(data => this.data = data);
  }

}


Alternative Approach: AsyncPipe for Simpler Cases
In cases where we can bind observables directly in the template, we prefer using Angular’s AsyncPipe, which handles subscription and unsubscription automatically.

Instead of,
this.dataService.getData().subscribe(data => {
  this.data = data;
});


Use in the template.
data$ = this.dataService.getData();

<div *ngIf="data$ | async as data">
  {{ data.name }}
</div>


Conclusion
Failing to unsubscribe from observables in Angular can lead to performance issues, duplicate API calls, and memory leaks. Using takeUntil with a Subject is a reliable and scalable solution, especially when combined with a base component class. For simpler use cases, Angular's AsyncPipe provides a clean and safe way to handle subscriptions in templates. Adhering to these practices keeps your Angular applications running smoothly, easy to maintain, and protected from those memory leaks that can improve performance. You will maintain both efficiency and code clarity as a result.



AngularJS Hosting Europe - HostForLIFE :: Using Angular Route Guards to Secure Routes

clock July 16, 2025 10:07 by author Peter

Depending on whether a user is logged in or has particular permissions, we frequently need to limit access to particular routes in Angular apps. Angular offers Route Guards, like CanActivate, to protect certain routes. In one of our projects, we had to prevent users from accessing the dashboard unless they were authenticated. We created an AuthGuard with CanActivate and added logic to check if the user token was locally stored. Everything was running fine until we released the app.


 Some users claimed that they were repeatedly taken to the login screen even if they were already logged in.

Reasons for the Problem
We found that timing was the cause of the problem. The guard attempted to verify the token before the validation was finished, even though the app had already called the API to validate the token at startup. It is therefore believed that the user was not authenticated.

How did we fix it?

Our AuthGuard logic has been modified to wait for validation to complete before granting or denying access. We used a shared AuthService with an isAuthenticated$ observable rather than just checking local storage.

Here’s how we adjusted the AuthGuard.
canActivate(): Observable<boolean> {
  return this.authService.isAuthenticated$.pipe(
    take(1),
    map(isAuth => {
      if (!isAuth) {
        this.router.navigate(['/login']);
        return false;
      }
      return true;
    })
  );
}


And in the AuthService, we updated the token status using a BehaviorSubject once the API response came back.
private authStatus = new BehaviorSubject<boolean>(false);

isAuthenticated$ = this.authStatus.asObservable();

validateToken() {
  // Call backend to validate token
  this.http.get('/api/validate-token').subscribe(
    () => this.authStatus.next(true),
    () => this.authStatus.next(false)
  );
}

We called validateToken() once in AppComponent during app initialization.

Conclusion
Route guards are essential for secure routing in Angular apps. But they must be carefully integrated with authentication logic, especially when token validation involves an async call. Using an observable approach helps in handling real-time state and avoiding premature navigation decisions.



AngularJS Hosting Europe - HostForLIFE :: Using Angular Route Guards to Secure Routes

clock July 14, 2025 08:33 by author Peter

Depending on whether a user is logged in or has particular permissions, we frequently need to limit access to particular routes in Angular apps. Angular offers Route Guards, like CanActivate, to protect certain routes. In one of our projects, we had to prevent users from accessing the dashboard unless they were authenticated. We created an AuthGuard with CanActivate and added logic to check if the user token was locally stored. Everything was running fine until we released the app.


Some users claimed that they were repeatedly taken to the login screen even if they were already logged in.

Reasons for the Problem
We found that timing was the cause of the problem. The guard attempted to verify the token before the validation was finished, even though the app had already called the API to validate the token at startup. It is therefore believed that the user was not authenticated.

How did we fix it?
Our AuthGuard logic has been modified to wait for validation to complete before granting or denying access. We used a shared AuthService with an isAuthenticated$ observable rather than just checking local storage.

Here’s how we adjusted the AuthGuard.

canActivate(): Observable<boolean> {
  return this.authService.isAuthenticated$.pipe(
    take(1),
    map(isAuth => {
      if (!isAuth) {
        this.router.navigate(['/login']);
        return false;
      }
      return true;
    })
  );
}


And in the AuthService, we updated the token status using a BehaviorSubject once the API response came back.
private authStatus = new BehaviorSubject<boolean>(false);

isAuthenticated$ = this.authStatus.asObservable();

validateToken() {
  // Call backend to validate token
  this.http.get('/api/validate-token').subscribe(
    () => this.authStatus.next(true),
    () => this.authStatus.next(false)
  );
}


We called validateToken() once in AppComponent during app initialization.

Conclusion
Route guards are essential for secure routing in Angular apps. But they must be carefully integrated with authentication logic, especially when token validation involves an async call. Using an observable approach helps in handling real-time state and avoiding premature navigation decisions.



Node.js Hosting - HostForLIFE :: Building a Simple REST API in Node.js (GET, POST, PUT, DELETE)

clock July 10, 2025 08:19 by author Peter

Node.js is a robust framework for JavaScript server-side application development. GET, POST, PUT, and DELETE are the fundamental methods of every CRUD (Create, Read, Update, Delete) action, and we'll show you how to create a basic REST API that supports them in this article.

To keep things clear and easy, we'll use the well-liked Express framework.

First, start a Node.js project
To begin, make a new folder for your project and set up npm for it.

mkdir nodejs-api-demo
cd nodejs-api-demo
npm init -y


Then, install Express,
npm install express

Step 2. Create the API Server
Create a file named server.js and write the following code.
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json()); // Middleware to parse JSON
let items = []; // Sample in-memory data store
// GET all items
app.get('/api/items', (req, res) => {
    res.json(items);
});
// POST a new item
app.post('/api/items', (req, res) => {
    const newItem = {
        id: Date.now(),
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json(newItem);
});

// PUT (update) an item by ID
app.put('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const index = items.findIndex(item => item.id === id);

    if (index !== -1) {
        items[index].name = req.body.name;
        res.json(items[index]);
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// DELETE an item by ID
app.delete('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const initialLength = items.length;
    items = items.filter(item => item.id !== id);

    if (items.length < initialLength) {
        res.json({ message: 'Item deleted' });
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// Hello World Endpoint
app.get('/', (req, res) => {
    res.send('Hello, World!');
});
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});


Step 3. Run Your API
Start your server using.

node server.js
Open your browser and go to:http://localhost:3000/ You should see "Hello, World!"

Use tools like Postman, Insomnia, or curl to test other endpoints:

  • GET http://localhost:3000/api/items
  • POST http://localhost:3000/api/items with JSON body: { "name": "Apple" }
  • PUT http://localhost:3000/api/items/123456789 with JSON: { "name": "Banana" }
  • DELETE http://localhost:3000/api/items/123456789

Summary
In this tutorial, you learned how to.

  • Initialize a Node.js project
  • Install and use Express.js
  • This setup is great for learning. For production, consider connecting to a real database, such as MongoDB, PostgreSQL, or MySQL.
  • Handle JSON data and HTTP methods (GET, POST, PUT, DELETE)
  • Build a basic in-memory CRUD API


Node.js Hosting - HostForLIFE :: Knowing Node.js's Event Loop, Callbacks, and Promises

clock July 3, 2025 08:00 by author Peter

The ability of Node.js to manage asynchronous processes is a major factor in its strength for creating quick, scalable network applications. You've probably heard of concepts like promises, callbacks, and event loops if you've ever dealt with Node.js.

In this post, we'll simplify these, go over actual code samples, and discuss how they all work together in the context of asynchronous programming.

Asynchronous programming: what is it?
JavaScript (as well as Node.js) only handles one instruction at a time since it is single-threaded. Unless we handle it asynchronously, if one operation (such as reading a file or sending a network request) takes a long time, it may prevent all other tasks from operating. Node.js can manage operations like file I/O, database queries, and API calls thanks to asynchronous programming, which keeps the application from stopping altogether.

The Event Loop: Node's Brain
The event loop is a mechanism in Node.js that allows it to perform non-blocking I/O operations. It listens for events and runs tasks from different queues (like timers or promise resolutions).

How does it work?

  • Executes synchronous code first.
  • Handles microtasks (like Promise.then()).
  • Then processes macrotasks (like setTimeout).
  • Repeats the cycle.

Example
console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise callback');
});
console.log('End');


Output
Start
End
Promise callback
Timeout callback


Why?

  • Promise.then() is a microtask, executed right after the synchronous code.
  • setTimeout() is a macrotask, executed after microtasks.

Callbacks: The Classic Asynchronous Tool
What is a Callback?

A callback is a function passed as an argument to another function. It’s executed when the first function completes - often asynchronously.
const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log(data);
});

Callback Hell
As you nest callbacks deeper, code can become hard to manage.
doTask1((res1) => {
  doTask2(res1, (res2) => {
    doTask3(res2, (res3) => {
      console.log(res3);
    });
  });
});


This “pyramid of doom” led to the evolution of promises.
Promises: A Modern Alternative

What is a Promise?
A promise is an object representing the eventual completion or failure of an asynchronous operation.
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});
myPromise
  .then((value) => console.log(value))
  .catch((err) => console.error(err));

Promise States

  • Pending: Initial state.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.

Promises in Action
function asyncTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('Task Done'), 2000);
  });
}
asyncTask().then(console.log); // Outputs "Task Done" after 2 seconds


Async/Await: Cleaner Syntax with Promises

Introduced in ES2017, async/await allows you to write asynchronous code like it’s synchronous.
async function fetchData() {
  try {
    const data = await asyncTask();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
fetchData();

This is still based on promises, but it's easier to read and write.

Event Loop + Promises + Callbacks: Putting It Together

console.log('Start');

setTimeout(() => {
  console.log('setTimeout');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise');
});

process.nextTick(() => {
  console.log('nextTick');
});
console.log('End');

Output
Start
End
nextTick
Promise
setTimeout

Execution order

  • Synchronous: Start, End
  • process.nextTick() (before promises)
  • Promises
  • Timers like setTimeout

Summary Table

Concept Purpose Queue
Event Loop Runs and manages all tasks          —
Callback Function called after async operation Callback queue
Promise Handles future values (success/failure) Microtask queue
setTimeout Delay execution of a task Macrotask queue
process.nextTick Runs after the current phase, before promises Microtask queue (special)

Conclusion

Node.js manages concurrency via non-blocking, asynchronous APIs and a clever event loop rather than threads. The event loop, promises, and callbacks are all crucial for creating Node.js applications with great performance. You will soon be able to create async code with confidence if you start small, try out samples, and gradually develop your mental model.



Node.js Hosting Europe - HostForLIFE :: Key Features of Node.js: A Clear Explanation

clock July 1, 2025 07:24 by author Peter

An open-source, cross-platform runtime environment called Node.js enables server-side JavaScript execution. It is incredibly fast because it is based on Chrome's V8 engine. Node.js's non-blocking, event-driven architecture is one of its strongest features; it makes it easier to create high-performance applications. Because we can use the same language-JavaScript-for both front-end and back-end development, many Indian developers.

Why Node.js is So Popular: 7 Key Features Explained?
Speed, scalability, and performance are essential for creating contemporary web applications in the fast-paced digital world of today. Node.js excels in this situation. Node.js has grown to be one of the most popular platforms since its launch, used by both developers and businesses, ranging from startups to internet behemoths like Netflix, PayPal, and LinkedIn.

1. Single-Threaded but Super Efficient
Node.js operates on a single-threaded event loop, in contrast to conventional server models that employ many threads. This implies that thousands of requests can be handled concurrently without requiring the creation of a new thread for each one. I/O-intensive applications like as file upload systems, chat apps, and streaming services are best suited for this.

2. Asynchronous and Non-Blocking
In Node.js, operations like reading files or querying a database do not block the main thread. Instead, they run in the background and notify when the task is complete. This non-blocking nature allows other tasks to continue running smoothly, perfect for high-performance apps.

3. Event-Driven Architecture
Everything in Node.js revolves around events. Instead of waiting for a process to complete, Node.js listens for events and responds accordingly. This event-driven nature improves performance and helps build scalable applications.

4. Powered by Google’s V8 Engine
Node.js uses Google’s powerful V8 JavaScript engine, the same engine used in Chrome. It compiles JavaScript directly into machine code, making it extremely fast and efficient.

5. Cross-Platform Support

Whether you are using Windows, macOS, or Linux, Node.js works seamlessly across platforms. This makes development flexible and accessible to a wider range of developers.

6. NPM – Node Package Manager
With Node.js, you get access to NPM, the world’s largest software registry. It contains thousands of free packages and libraries that you can easily install and use in your projects, saving a lot of development time.

7. Built for Real-Time Applications

One of the biggest strengths of Node.js is its real-time capabilities. Whether you’re building a messaging app, online multiplayer game, or live tracking system, Node.js offers the perfect foundation for real-time communication.

Conclusion
Node.js is a comprehensive ecosystem that enables developers to create quick, scalable, and contemporary apps. It is not just another server-side technology. It is perfect for today's digital demands because of its single-threaded paradigm, asynchronous nature, and real-time characteristics. If you're an Indian developer who wants to improve your backend skills, learning Node.js can lead to a lot of options.



AngularJS Hosting Europe - HostForLIFE :: Use the ASP.NET Web API in Angular to Retrieve Data From a Database

clock June 25, 2025 09:45 by author Peter

In this article, I will explain how to call ASP.NET web API in your Angular project step by step. You need to enable CORS in your web API and fetch data from web API. It is easy to call API in Angular.


Step 1
Open SQL server of your choice and create a table and insert some records.

    CREATE TABLE [dbo].[Employee](  
        [Employee_Id] [int] IDENTITY(1,1) NOT NULL,  
        [First_Name] [nvarchar](50) NULL,  
        [Last_Name] [nvarchar](50) NULL,  
        [Salary] [money] NULL,  
        [Joing_Date] [nvarchar](50) NULL,  
        [Department] [nvarchar](50) NULL,  
     CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
    (  
        [Employee_Id] ASC  
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
    ) ON [PRIMARY]  
      
    GO  

Step 2

Open Visual Studio, click on New Project and create an empty web API application project.

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in the below screenshot.

After clicking on OK one more window will appear; choose empty, check on empty Web API checkbox then click on OK as shown in the below screenshot

After clicking OK, the project will be created with the name of WebAPICRUD_Demo.

Step 3
Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

After clicking on a New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory you can give any name) and click on Add.

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next.

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter a dot (.). Choose your database and click on OK.

The connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.

After clicking on NEXT another window will appear to choose database table name as shown in the below screenshot then click on Finish. Entity framework will be added and the respective class gets generated under the Models folder.

Following class will be added,
    namespace WebAPICURD_Demo.Models  
    {  
        using System;  
        using System.Collections.Generic;  
          
        public partial class Employee  
        {  
            public int Employee_Id { get; set; }  
            public string First_Name { get; set; }  
            public string Last_Name { get; set; }  
            public Nullable<decimal> Salary { get; set; }  
            public string Joing_Date { get; set; }  
            public string Department { get; set; }  
        }  
    }  

Step 4
Right click on Controllers folder, select Add, then choose Controller as shown in the below screenshot.


After clicking on the controller a window will appear to choose Web API 2 Controller-Empty, click on Add.


Fetch Data From Database Using ASP.NET Web API In Angular
After clicking on Add, another window will appear with DefaultController. Change the name to EmployeeController then click on Add. EmployeeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.


Complete code for controller
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Net.Http;  
    using System.Web.Http;  
    using WebAPICURD_Demo.Models;  
      
    namespace WebAPICURD_Demo.Controllers  
    {  
        public class EmployeeController : ApiController  
        {  
             
            private EmployeeEntities _db;  
            public EmployeeController()  
            {  
                _db =new EmployeeEntities();  
            }  
            public IEnumerable<Employee> GetEmployees()  
            {  
                return _db.Employees.ToList();  
            }  
        }  
    }  


Step 5
Now, enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command.
Install-Package Microsoft.AspNet.WebApi.Cors  

This command installs the latest package and updates all dependencies, including the core Web API libraries.

Step 6
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

Add namespace
using System.Web.Http.Cors;  

Add the following line of code,
    EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
    config.EnableCors(cors);  


Complete WebApiConfig.cs file code
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Http;  
    using System.Web.Http.Cors;  
      
    namespace WebAPICURD_Demo  
    {  
        public static class WebApiConfig  
        {  
            public static void Register(HttpConfiguration config)  
            {  
                // Web API configuration and services  
                  
                // Web API routes  
                config.MapHttpAttributeRoutes();  
      
                config.Routes.MapHttpRoute(  
                    name: "DefaultApi",  
                    routeTemplate: "api/{controller}/{id}",  
                    defaults: new { id = RouteParameter.Optional }  
                );  
      
                EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
                config.EnableCors(cors);  
            }  
        }  
    }  


Step 6
Open Visual Studio Code and create a new Angular project.
    ng new MyDemo  

Compile your project
    cd MyDemo  

Open your project in the browser,
    ng serve --open  

Step 7
Install bootstrap in your project and import in style.css file,
    npm install bootstrap –save  

    @import 'node_modules/bootstrap/dist/css/bootstrap.min.css';  


Step 8
Open terminal create component,
    ng g c employee-list  

Step 9
Open app.module.ts file and import httpModule
    import { BrowserModule } from '@angular/platform-browser';  
    import { NgModule } from '@angular/core';  
    import {HttpClientModule, HttpClient} from '@angular/common/http';  
      
    import { AppComponent } from './app.component';  
    import { from } from 'rxjs';  
    import { EmployeeListComponent } from './employee-list/employee-list.component';  
      
    @NgModule({  
      declarations: [  
        AppComponent,  
        EmployeeListComponent  
      ],  
      imports: [  
        BrowserModule,  
        HttpClientModule  
      ],  
      providers: [],  
      bootstrap: [AppComponent]  
    })  
    export class AppModule { }  


Step 10
Open employee-list component.ts file and add the following code,
    import { HttpClientModule, HttpClient } from '@angular/common/http';  
    import { Component, OnInit } from '@angular/core';  
      
    @Component({  
      selector: 'app-employee-list',  
      templateUrl: './employee-list.component.html',  
      styleUrls: ['./employee-list.component.css']  
    })  
    export class EmployeeListComponent implements OnInit {  
      
      constructor(private httpService: HttpClient) { }  
      employees: string[];  
      ngOnInit() {  
        this.httpService.get('http://localhost:52202/api/employee').subscribe(  
          data => {  
           this.employees = data as string [];  
          }  
        );  
      }  
      
    }  


Step 11
open employee-list.component.html and add the following code,
    <div class="container py-5">  
        <h3 class="text-center text-uppercase">List of Employees</h3>  
        <table class="table table-bordered table-striped">  
            <thead>  
                <tr class="text-center text-uppercase">  
                    <th>Employee ID</th>  
                    <th>First Name</th>  
                    <th>Last Name</th>  
                    <th>Salary</th>  
                    <th>Joining Date</th>  
                    <th>Department</th>  
                  </tr>  
            </thead>  
            <tbody>  
              <tr *ngFor="let emp of employees">  
                <td>{{emp.Employee_Id}}</td>  
                <td>{{emp.First_Name}}</td>  
                <td>{{emp.Last_Name}}</td>  
                <td>{{emp.Salary}}</td>  
                <td>{{emp.Joing_Date}}</td>  
                <td>{{emp.Department}}</td>  
              </tr>  
            </tbody>  
          </table>  
        </div>  


Step 12
Add your employee-list.component.html selector in app.component.html
    <app-employee-list></app-employee-list>  

Step 13
Run your project in browser.



AngularJS Hosting Europe - HostForLIFE :: New Development Site Angular

clock June 17, 2025 09:19 by author Peter

Note: The publication date of this article is January 10, 2025. This article series is unquestionably an AI result or byproduct.  This piece might represent a change in my writing style since it makes use of AI results that I understand, like those related to StackBlitz | Instant Dev Environments, to make it easier to write and easier to read. Angular first launched in 2016, Angular's home page used to be at angular.io for years. Recently, I found that a new Angular Development Site has been created. This article records some info about this event. 

Official Home: May, 2024

Previous Sites:
Angular - Introduction to the Angular docs --- Angular.io --- v17

Angular - Introduction to the Angular docs --- Angular.io --- v18


Tutorial:

Tutorials • Angular



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in