Node.js Crash Course Tutorial #2 - Node.js Basics

3 min read 1 month ago
Published on Aug 03, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial provides a comprehensive overview of Node.js basics, including how to run JavaScript files on your computer, understand the global object, manage modules, utilize the file system, and work with streams. This knowledge is essential for developing server-side applications and understanding Node.js functionality.

Chapter 1: Node Basics

To begin using Node.js on your computer:

  1. Open a Terminal: This can be an integrated terminal in VS Code or a command prompt.
  2. Run a JavaScript File: Create a JavaScript file (e.g., test.js) and execute it using the command:
    node test.js
    
  3. Write JavaScript Code: For example, create a simple greeting function:
    function greet(name) {
        console.log(`Hello, ${name}`);
    }
    
    greet('Mario');
    greet('Jasha');
    
  4. Execute Again: Run the file again to see the output.

Chapter 2: The Global Object

In Node.js, the global object differs from the browser's window object.

  1. Access Global Object: Use global instead of window.
  2. Log the Global Object: Create a file (e.g., global.js) and log the global object:
    console.log(global);
    
  3. Use Global Methods: For instance, using setTimeout:
    global.setTimeout(() => {
        console.log('Timeout executed');
    }, 3000);
    
  4. Access Directory and File Names:
    • Use __dirname for the directory path.
    • Use __filename for the file path.
    console.log(__dirname);
    console.log(__filename);
    

Chapter 3: Modules and Require

Node.js allows you to split code into multiple files for better organization.

  1. Create Module Files: Create people.js with:
    const people = ['Mario', 'Jasha'];
    console.log(people);
    module.exports = people;
    
  2. Import the Module: In another file (e.g., modules.js):
    const people = require('./people');
    console.log(people);
    
  3. Export Multiple Items: You can export an object for multiple exports:
    module.exports = {
        people,
        ages: [25, 30]
    };
    
  4. Destructure Imports:
    const { people, ages } = require('./people');
    

Chapter 4: Node and the File System

Node.js provides the fs module to interact with the file system.

  1. Import the File System Module:
    const fs = require('fs');
    
  2. Read Files: Use fs.readFile:
    fs.readFile('./docs/blog1.txt', 'utf8', (err, data) => {
        if (err) {
            console.log(err);
            return;
        }
        console.log(data);
    });
    
  3. Write Files: Use fs.writeFile:
    fs.writeFile('./docs/blog1.txt', 'New content', (err) => {
        if (err) {
            console.log(err);
            return;
        }
        console.log('File written');
    });
    
  4. Create and Delete Directories:
    • Create a directory:
      fs.mkdir('./assets', (err) => {
          if (err) {
              console.log(err);
              return;
          }
          console.log('Directory created');
      });
      
    • Delete a directory:
      fs.rmdir('./assets', (err) => {
          if (err) {
              console.log(err);
              return;
          }
          console.log('Directory deleted');
      });
      

Chapter 5: Streams and Buffers

Streams allow you to read large files efficiently without waiting for the entire file to load.

  1. Create a Read Stream:
    const readStream = fs.createReadStream('./docs/blog3.txt', { encoding: 'utf8' });
    readStream.on('data', (chunk) => {
        console.log('New chunk received:', chunk);
    });
    
  2. Create a Write Stream:
    const writeStream = fs.createWriteStream('./docs/blog4.txt');
    writeStream.write('Hello World\n');
    writeStream.write('New chunk\n');
    
  3. Use Pipe to Stream Data:
    readStream.pipe(writeStream);
    

Conclusion

In this tutorial, you learned the fundamentals of Node.js, including how to run JavaScript files, utilize the global object, manage modules, interact with the file system, and handle streams. These concepts form the foundation for building server-side applications with Node.js. Next, consider exploring the HTTP module to create servers or dive deeper into Node.js features for more advanced applications.