Lecture on Node.js Fundamentals

Jul 1, 2024

Lecture on Node.js Fundamentals

Introduction to Node.js

  • Node.js is an open-source, cross-platform runtime environment for executing JavaScript code outside of a browser.
  • Commonly used for building backend services (APIs) to power client applications (web or mobile apps).
  • Node.js is ideal for highly scalable, data-intensive, and real-time backend services.

Advantages of Node.js

  • Ease of Use: Simple to get started for prototyping and agile development.
  • Performance: Can build super-fast and highly scalable services.
    • Example: PayPal's switch from Java and Spring to Node resulted in doubling requests per second and improving response times by 35%.
  • JavaScript: Usage of JavaScript on both the front-end and back-end offers cleaner and more consistent code, allowing front-end developers to become full-stack developers.
  • Ecosystem: Largest ecosystem of open-source libraries, offering pre-built components to accelerate development.

Node.js Architecture

  • Runtime Environment: Executes JavaScript code outside the browser using the V8 engine, which converts JS code into machine code.
  • JavaScript Engines: V8 engine (used in Chrome and Node.js), SpiderMonkey (Firefox), Chakra (Edge).
  • Environment Objects: Unlike browsers that have window/document objects, Node.js provides different objects for working with the file system, network, etc.

Asynchronous Architecture

  • Non-blocking: Node.js uses an asynchronous, non-blocking architecture.
    • Similar to a waiter in a restaurant taking multiple orders without waiting for one order to be completed.
    • Single thread handles multiple requests by delegating operations to the system (e.g., file system or database).
  • Blocking Architecture: Traditional synchronous systems like ASP.NET or Rails use blocking architecture, leading to inefficient resource usage.
  • Event Queue: Node.js uses an event queue to manage completed operations, making it more efficient for I/O-bound tasks.

Installing Node.js

  • Check if Node.js is installed: node --version
  • Download from nodejs.org: Choose the LTS version.
  • Commonly used editors: VS Code, Sublime, Atom.
  • Basic Usage: Create a JS file, define functions, and execute using the node app.js command.

Node.js Module System

  • Modules: Every file in a Node app is considered a module; variables and functions are scoped to their file.
  • Exporting Modules: Use module.exports to expose functions or variables outside the module.
  • Loading Modules: Use require to load other modules.
  • Core modules include fs, http, os, path, etc.

Example Modules

  • Path Module: Provides utilities for working with file and directory paths.
    • Usage: const path = require('path');
  • OS Module: Provides methods for getting information about the operating system.
    • Usage: const os = require('os');
  • File System Module: Provides methods for interacting with the file system.
    • Usage: const fs = require('fs');

Event Emissions

  • Event Emitter: Core of Node.js event-driven architecture.
  • Creating and Handling Events: Use eventEmitter.on to handle events and eventEmitter.emit to raise events.
  • Custom Events: Extend EventEmitter to create custom event-driven systems.

HTTP Module

  • Building a Web Server:

    • Use http.createServer to create a basic web server.
    • Use the request and response objects to handle HTTP requests and responses.
    const http = require('http');
    const server = http.createServer((req, res) => {
      if (req.url === '/') {
        res.write('Hello World');
        res.end();
      } else if (req.url === '/api/courses') {
        res.write(JSON.stringify([1, 2, 3]));
        res.end();
      }
    });
    server.listen(3000);
    console.log('Listening on port 3000...');
    

Conclusion

  • Node.js is powerful for creating scalable, efficient web applications using JavaScript across both the client and server.
  • Emphasis on mastering the fundamentals and leveraging core modules.
  • The ecosystem and community support make it a strong choice for modern web development.