Ankita.eth
GithubContact
  • About Ankita
  • experience
    • TECHNOLOGIES
    • Frontend
      • Javascript
      • React
      • NextJS
      • HTML & CSS
      • UI Libraries & Frameworks
        • Tailwind CSS
        • Comprehensive Guide to UI Libraries and Frameworks
    • Backend
      • Node.js
      • Express.js
    • Database
      • Mongodb, Mongoose
      • PostgresSQl
      • MySQL
    • Packege Mangers
      • NPM-Node Packege Manager
      • Yarn
      • Yarn 2 (Berry)
      • PNPM
      • BUN
      • Commands cheatsheet
    • API Providers
      • Alchemy
      • Telegram Bot
      • CoinMarket
      • Thirdweb
      • Infura
      • Moralis
    • DevOps/Infrastructure
      • Docker
      • Kubernetes
      • CI/CD
      • Docker Swam
    • Protocols
      • ERCs & EIPs
        • ERC-20
        • ERC-721
        • ERC-1155
        • ERC-4337
        • ERC-6551
        • ERC-777
        • ERC-3643
        • EIP-7702
        • ERC-7715
        • ERC-7739
        • EIP-6780
        • EIP-5792
        • ERC-4626
        • EIP-1559
        • ERC-404
        • ERC-3643
        • ERC-223
    • Web3 Toolkits
      • Foundry
      • Hardhat
      • RemixIDE
    • Messaging/Caching
      • Kafka
      • Redis
      • Sendgrid
    • Blockchain
      • Solana
      • Ethereum
      • Polygon & Zero knowldge Proof
      • Bitcoin
      • Solidity
    • Deployment Platforms
      • AWS
      • Vercel
      • Heroku, Render
      • Domain setup
  • SDKs
    • Google Cloud SDK
    • AWS SDK
    • Firebase SDK
  • EOF EVM Object Format
  • Articles
    • Medium Articles
    • 🌐 My Work
  • 📞 Get in Touch
Powered by GitBook
On this page
  • Introduction to Node.js 🌟
  • Node.js Architecture 🏗️
  • Parts of Node.js
  • Core Concepts 🧠
  • Advanced Concepts 🚀
  • Conclusion 🎓

Was this helpful?

  1. experience
  2. Backend

Node.js

Introduction to Node.js 🌟

Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server-side, enabling the creation of scalable and high-performance web applications.

Why Use Node.js? 🤔

  • Asynchronous and Event-Driven: Perfect for non-blocking, event-driven servers

  • Fast: Executes code quickly due to its V8 JavaScript Engine

  • Single-threaded but Highly Scalable: Can handle a huge number of simultaneous connections

  • No Buffering: Node.js applications never buffer any data

  • Large Ecosystem: npm (Node Package Manager) has a vast library of open-source packages

Installation Guide 🛠️

Follow these steps to install Node.js:

  1. Visit the official Node.js website: https://nodejs.org

  2. Download the installer for your operating system

  3. Run the installer and follow the prompts

  4. Verify installation by opening a terminal and running:

    node --version
    npm --version

Node.js Architecture 🏗️

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Here's a simplified diagram of its architecture:

Parts of Node.js

Core Concepts 🧠

1. Event Loop ⚙️

The event loop is the heart of Node.js. It allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.

const fs = require('fs');

// Asynchronous file read
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

console.log('This will be printed first!');

2. Modules 📦

Node.js uses the CommonJS module system. You can create and use modules to organize your code.

// math.js
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b
};

// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8

3. Streams 🌊

Streams are objects that let you read data from a source or write data to a destination continuously.

const fs = require('fs');
const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream);

readStream.on('end', () => {
  console.log('Read and write completed');
});

4. Buffers 🧊

Buffers are used to handle binary data in Node.js.

const buf = Buffer.from('Hello, World!', 'utf8');
console.log(buf.toString('hex')); // Output: 48656c6c6f2c20576f726c6421
console.log(buf.toString('base64')); // Output: SGVsbG8sIFdvcmxkIQ==

Advanced Concepts 🚀

1. Clustering 🖥️

Node.js clustering allows you to create child processes that run simultaneously, sharing the same server port.

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
  • Master process: The code runs as a master if cluster.isMaster is true. The master process is responsible for forking worker processes.

  • Workers: Each worker is a new Node.js process, created by cluster.fork(). Workers share the same server port but run on different CPU cores, enabling better resource utilization.

  • Restart workers: If a worker crashes, the master process listens to the exit event and restarts the worker using cluster.fork().

2. Worker Threads 🧵

Worker threads allow running JavaScript in parallel, useful for CPU-intensive tasks.

const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.on('message', (msg) => {
    console.log('From worker:', msg);
  });
  worker.postMessage('Hello, worker!');
} else {
  parentPort.on('message', (msg) => {
    console.log('From parent:', msg);
    parentPort.postMessage('Hello, parent!');
  });
}
  • Main thread: When isMainThread is true, the current thread is the main thread, which creates a new worker using the Worker constructor. The file to be executed in the worker thread is the same file (__filename), but it will run different code based on whether it's in the main thread or the worker thread.

  • Worker thread: In the worker, we receive workerData (input) and perform a CPU-intensive calculation. After the calculation is done, the result is sent back to the main thread using parentPort.postMessage().

  • Communication: The main thread listens for messages using the 'message' event, and error handling is done through the 'error' and 'exit' events.

3. Performance Optimization 🏎️

Optimizing Node.js applications involves various techniques:

  • Use asynchronous methods whenever possible

  • Implement caching strategies

  • Optimize database queries

  • Use compression for network responses

  • Implement load balancing

4. Security Best Practices 🔒

Ensuring the security of your Node.js application is crucial:

  • Keep dependencies up to date

  • Use HTTPS

  • Implement proper authentication and authorization

  • Validate and sanitize user inputs

  • Set appropriate HTTP headers

  • Use security linters like eslint-plugin-security

Conclusion 🎓

Node.js is a powerful platform that enables developers to build scalable and efficient applications. By mastering these concepts and continuously learning, you can become a proficient Node.js developer capable of tackling complex backend challenges.

PreviousBackendNextExpress.js

Last updated 9 months ago

Was this helpful?