Day 2: Understanding Core Modules and the Event Loop: Using Modules and npm

Day 2: Understanding Core Modules and the Event Loop: Using Modules and npm

Node.js core modules (e.g., fs, path, http, os)
Understanding the Event Loop
Synchronous vs Asynchronous programming in Node.js
Practical: Basic file operations using fs module (read, write, append)
Handling paths with path module
Timing events with setTimeout and setInterval

Event Loop in Node.js

What is the Event Loop?

  • Node.js uses an event-driven, non-blocking I/O model which makes it lightweight and efficient. The event loop is responsible for handling asynchronous operations. It allows Node.js to handle multiple operations without creating multiple threads.

Example of Event Loop:

console.log('Start');

setTimeout(() => {
  console.log('Timeout function executed');
}, 2000);

console.log('End');

Synchronous vs Asynchronous Programming

  • Synchronous:

    • Operations that block further code execution until the current task is finished. In Node.js, most operations can be done asynchronously to avoid blocking the event loop.

Example of Synchronous Code:

    const fs = require('fs');

    console.log('Start reading file...');
    const data = fs.readFileSync('example.txt', 'utf-8');
    console.log(data);
    console.log('Finished reading file.');
  • This code blocks further execution until the file is completely read.
  • Asynchronous:

    • Non-blocking operations that allow the rest of the program to run while waiting for a task (like reading a file) to complete.

Example of Asynchronous Code:

    const fs = require('fs');

    console.log('Start reading file...');
    fs.readFile('example.txt', 'utf-8', (err, data) => {
      if (err) throw err;
      console.log(data);
    });
    console.log('Finished reading file.');
  • Here, Node.js will continue executing other code (e.g., "Finished reading file.") while waiting for the file to be read.
  • 2. Practical:


    Basic File Operations with fs Module

    • fs (File System) module:

      • Allows working with the file system, such as reading, writing, and appending to files.

      • Reading a File (Asynchronous):

          const fs = require('fs');
        
          fs.readFile('example.txt', 'utf-8', (err, data) => {
            if (err) throw err;
            console.log('File contents:', data);
          });
        
      • Writing to a File (Asynchronous):

          const fs = require('fs');
        
          fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
            if (err) throw err;
            console.log('File written successfully.');
          });
        
      • Appending to a File (Asynchronous):

          const fs = require('fs');
        
          fs.appendFile('output.txt', '\nAppended text.', (err) => {
            if (err) throw err;
            console.log('Text appended successfully.');
          });
        

Handling Paths with path Module

  • path module:

    • Helps with working with file and directory paths. It's especially useful when you need to manipulate or join paths across platforms.

    • Joining Paths:

        const path = require('path');
      
        const fullPath = path.join(__dirname, 'files', 'example.txt');
        console.log('Full Path:', fullPath);
      
    • Getting File Name from Path:

        const path = require('path');
      
        const filePath = '/users/documents/example.txt';
        console.log('File Name:', path.basename(filePath));
      
    • Getting Directory Name from Path:

        const path = require('path');
      
        const filePath = '/users/documents/example.txt';
        console.log('Directory Name:', path.dirname(filePath));
      

Timing Events with setTimeout and setInterval

  • setTimeout: Runs a function after a certain delay (once).

      setTimeout(() => {
        console.log('This runs after 3 seconds');
      }, 3000); // 3000 milliseconds = 3 seconds
    
  • setInterval: Runs a function repeatedly after a specified interval.

      setInterval(() => {
        console.log('This runs every 2 seconds');
      }, 2000); // 2000 milliseconds = 2 seconds
    
  • Clearing Intervals:

      const intervalId = setInterval(() => {
        console.log('Repeating...');
      }, 1000);
    
      setTimeout(() => {
        clearInterval(intervalId);
        console.log('Stopped interval');
      }, 5000); // Stop after 5 seconds
    
  • Working with Modules and npm

  • 1. Theory:


    Modular Programming in Node.js

    • What is Modular Programming?

      • Modular programming is about breaking a program into smaller, reusable parts (called modules). Each module contains related functionality, making code easier to maintain and scale.
    • Node.js uses CommonJS module system, which includes:

      • require(): Used to load modules.

      • module.exports: Used to export functionality from a module so other files can use it.


CommonJS: How Modules Work in Node.js

  • Creating a module:

    • In Node.js, you can create your own module by writing code in a separate file and exporting the functionality you want to reuse.
  • Using require() to load a module:

    • To use a module in another file, you load it with require().

Example:

        // math.js (your custom module)
        function add(a, b) {
          return a + b;
        }

        function subtract(a, b) {
          return a - b;
        }

        // Exporting the functions
        module.exports = { add, subtract };
  • Now, you can use the add and subtract functions from math.js in another file:
        // main.js
        const math = require('./math');

        console.log(math.add(5, 3)); // Output: 8
        console.log(math.subtract(10, 7)); // Output: 3

What is npm and Package Management?

  • What is npm?

    • npm (Node Package Manager) is the default package manager for Node.js. It helps install, manage, and share reusable packages of code.

    • npm allows you to easily download and integrate thousands of third-party libraries (packages) like lodash, axios, etc., into your project.

  • Package Management:

    • Packages are collections of code that can be easily installed and managed using npm. They are stored in a registry (like npm's registry) and can be added to your project with simple commands.

Introduction to package.json and Dependencies

  • What is package.json?

    • package.json is a file that holds metadata about your Node.js project (like project name, version, and dependencies). It is automatically generated when you run the npm init command.
  • Dependencies:

    • Dependencies are packages your project relies on. They are listed in package.json so they can be easily installed on any machine using npm install.

3. Tasks for Day 2:

  1. Task 1: File Operations

    • What to do:

      • Create a new file called notes.txt and write "Learning Node.js" into it.

      • Read and display the content of notes.txt.

      • Append "Node.js is awesome!" to the same file and read it again.

  2. Task 2: Path Operations

    • What to do:

      • Use the path module to print the full path of your notes.txt file.

      • Extract and print only the file name from the path.

      • Extract and print the directory name from the path.

  3. Task 3: Timing Events

    • What to do:

      • Write a setTimeout function to print "Hello after 3 seconds."

      • Use setInterval to print "Learning is fun!" every 2 seconds and stop it after 10 seconds using clearInterval.

  4. Reflection:

    • Write a paragraph about your understanding of synchronous and asynchronous programming. Explain the difference in your own words.

Additional Resources:

  • Node.js Official Documentation

  • Understanding the Node.js Event Loop


Summary:

  • Theory: Focus on core modules like fs, path, and the Node.js event loop.

  • Practical: Perform file operations, handle paths, and understand timing events with setTimeout and setInterval.

  • Tasks: Reinforce learning by writing and manipulating files, handling paths, and experimenting with asynchronous timers.