Introduction to Node.js Study Notes
Learning Objectives
- Demonstrate a comprehensive understanding of the key features of Node.js.
- Successfully install and utilize Node.js and Visual Studio Code (VS Code).
- Understand the concepts of event-driven architecture and the implementation of callbacks.
- Utilize the Node.js Module System and the Node Package Manager (NPM).
Introduction to Node.js
- Node.js is defined as an open-source and cross-platform JavaScript runtime environment.
- It provides the capability for programmers to execute JavaScript code on the server-side, which is outside of a traditional web browser environment.
- Node.js is built on the Chrome V8 JavaScript engine.
- Every web browser possesses its own JavaScript engine; specifically, the Google Chrome browser utilizes the V8 engine.
- Node.js architecture is characterized by being event-driven and non-blocking.
- It operates on a single-threaded model and processes events using callbacks.
- Connection effectiveness: This architecture is extremely effective and scalable for managing concurrent connections and processes.
- Non-blocking Example: HTTP calls made to a server from Node.js code are non-blocking and asynchronous. The code does not wait for the response; instead, it handles the response only when it arrives using a callback model.
- Downloading Node.js:
- Users should visit nodejs.org.
- The "LTS" (Long Term Support) version is recommended for most users.
- Windows Installation:
- Download the
.msi file and run it.
- Follow the Node.js Setup wizard and select the default settings. - Mac Installation:
- Apple users can utilize the Homebrew package manager.
- Homebrew can be downloaded and installed from brew.sh.
- Once Homebrew is installed, use the command:
brew install nodejs. - Verification:
- To verify a successful installation, type
node -v in a command prompt or terminal to check the version number. - Executing Files:
- Node.js can execute any JavaScript file from the command prompt using the command
node file.js.
- Example: Create a file named hello.js. Navigate to its directory in the terminal and run node hello.js. - Visual Studio Code Setup:
- Download and install at code.visualstudio.com via the Setup wizard.
- Use the File menu to navigate to any directory on the machine to write code.
- Use the keyboard shortcut
Ctrl ~ to open the integrated TERMINAL window within Visual Studio Code to execute files using node commands.
Event-Driven Architecture and Callbacks
- Node.js is based on a non-blocking, event-driven architecture.
- This design is highly effective for managing concurrent connections and Input/Output (I/O) activities.
- Single-Threaded Model: This architecture eliminates the need to create new threads for every individual connection, allowing a single event loop to manage multiple concurrent connections.
- Event Loop: Used by Node.js to control events and callbacks. It continuously scans for events, such as incoming requests or finished I/O operations, which then trigger specific callbacks.
- Asynchronous Handling: All I/O operations in Node.js are carried out asynchronously via callbacks. This enables programs to carry out other tasks without waiting for an I/O activity to finish.
- Common Asynchronous Examples: Reading from a file, sending an HTTP request, or querying a database.
- Definition of a Callback: A callback is a function invoked after an asynchronous operation is finished and is supplied as an input to another function.
- Non-blocking execution detailed: When an asynchronous operation is initiated (like reading a file), the code does not wait for completion; it continues executing the remaining code. Once the operation is complete, the callback function is called to handle results or errors.
Code Example: fs.readFile
- The following example illustrates how callbacks are used with the built-in File System (
fs) module:
const fs = require('fs');
// Asynchronous file read operation
fs.readFile('file.txt', 'utf8', function(err, data) {
if (err) {
// Handle error
console.error('Error reading file:', err);
} else {
// Process the data
console.log('File content:', data);
}
});
// Code execution continues here before the file read operation is complete
console.log('Reading file...');
- Technical Details of the Example:
-
fs.readFile takes three arguments: the file name (file.txt), the character encoding (utf8), and the callback function.
- The callback function itself takes two parameters: err (for any error that occurred) and data (containing the file's content upon success).
- Node.js follows an "error-first" convention: the first parameter of the callback is reserved for an error object. If no error occurs, this parameter will be null or undefined.
Node.js Module System
- Definition: A Node.js module is a file containing JavaScript code that defines a set of functions, objects, or variables.
- Every JavaScript file in Node.js is considered a module.
- Purpose: Modules allow for reusable code that can be imported to enhance functionality, speed, and ease of development.
- The
require() Function:
- This is a built-in function used to include external modules existing in separate files.
- The require() statement reads a JavaScript file, executes it, and returns the export object.
- Use relative paths: require('/relative path of the 2nd file').
- It can include custom .js files, built-in Node.js APIs, or third-party libraries.
Core and External Modules
- Core Modules:
- Included in the Node.js standard library.
- They do not require additional package installation.
- Key Examples:
-
fs: Handles file system operations (Reading/Writing).
- http: Used to create HTTP servers and clients.
- path: Handles and transforms file paths.
- os: Provides information about the operating system. - Reading and Writing Files with Core Module
fs:
- fs.readFile() parameters: File path, character encoding, and a callback function (data/error).
- fs.writeFile() parameters: File name with complete path, data to be written, and a callback function (fires in case of error). - External Modules:
- Produced by the community and kept in the npm registry.
- Installed and utilized via package managers.
- Key Examples:
-
Axios: Used for sending HTTP requests.
- Moment.js: A time-zone utility for handling dates and times.
- Mongoose: Used for interacting with MongoDB databases.
Node Package Manager (NPM)
- npm is the package manager for Node.js and contains three components:
- 1. Website: Used to discover packages (npmjs.com).
- 2. Command Line Interface (CLI): Used for running commands from a terminal (installed automatically with Node.js). Use
npm -v to check the version.
- 3. Registry: A vast public database of JavaScript libraries and meta-information. - Creating a Project (Package) with npm:
- Step 1: Create a new project directory and navigate to it (
cd).
- Step 2: Initialize the project using npm init. This leads through prompts (name, version, description, entry point, etc.).
- Step 3: Install dependencies using npm install <package_name>. Example: npm install express.
- Installing a package (like Express or Moment) updates the dependencies section of the package.json file.
- Step 4: Use the packages by importing them: const express = require('express');.
Advanced Module Usage: Exports
- The biological counterpart to
require is exports. - Encapsulation: By default, a module is encapsulated. Functions defined in one module (e.g.,
calculator.js) cannot be called in another (e.g., hello.js) unless they are exported. module.exports: Functions/objects must be attached to module.exports to be accessible elsewhere.- Export Variations:
-
exports alone refers to module.exports.
- exports.propertyName: You can assign function definitions to specific properties using fat arrow notation.
- Example: A file Calculator2.js might return an exports object with properties like .add, .subtract, .multiply, and .divide. exports and require() are complementary and function together to manage the scope and reuse of code across the application.