1. Introduction to Node.js
Node.js is a runtime environment that allows you to run JavaScript on the server side. Built on Google Chrome's V8 JavaScript engine, Node.js is designed for building scalable and efficient network applications. It uses an event-driven, non-blocking I/O model, which makes it lightweight and efficient, especially for data-intensive real-time applications that run across distributed devices.
2. Installing Node.js
Before you can start developing with Node.js, you need to install it on your system. Node.js comes with a package manager called npm (Node Package Manager), which helps manage libraries and dependencies.
2.1 Installation Steps
To install Node.js, follow these steps:
- Windows: Download the installer from the official Node.js website and follow the installation prompts.
- macOS: Use a package manager like Homebrew:
brew install node
. - Linux: Use a package manager like apt:
sudo apt install nodejs
andsudo apt install npm
.
2.2 Verifying Installation
After installation, verify that Node.js and npm are installed correctly by running the following commands in your terminal:
node -v
npm -v
These commands should output the versions of Node.js and npm installed on your system.
3. Node.js Modules
Modules are the building blocks of a Node.js application. A module in Node.js is a reusable block of code whose existence does not impact other code. Node.js has a set of built-in modules, such as fs
(for file system operations), http
(for creating servers), and path
(for handling file paths). Additionally, you can create your own modules and import third-party modules using npm.
3.1 Using Built-In Modules
To use a built-in module, you require it in your application:
3.1.1 Example: Using the fs
Module
const fs = require('fs');
// Read a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
In this example, the fs
module is used to read the contents of a file asynchronously.
3.2 Creating Your Own Modules
You can create custom modules in Node.js by exporting functions, objects, or variables from a file and importing them into another file.
3.2.1 Example: Creating and Using a Custom Module
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2
Here, a custom module named math
is created with two functions, add
and subtract
. This module is then imported and used in another file.
4. Creating a Simple Server
One of the core functionalities of Node.js is the ability to create a server. The http
module is commonly used for this purpose. A Node.js server listens for requests on a specified port and sends responses.
4.1 Example: Basic HTTP Server
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
// The server listens on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
This example creates a basic HTTP server that responds with "Hello, World!" when accessed through a browser at http://127.0.0.1:3000/
.
5. Asynchronous Programming in Node.js
Node.js is designed to handle asynchronous operations efficiently. Asynchronous programming is crucial in Node.js, as it helps manage tasks like I/O operations, which can take time to complete. Node.js uses callbacks, promises, and async/await to handle asynchronous code.
5.1 Callbacks
A callback is a function passed as an argument to another function, which is then executed after the completion of an asynchronous operation.
5.1.1 Example: Callback
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 2000);
}
fetchData((data) => {
console.log(data); // Output after 2 seconds: Data received
});
5.2 Promises
Promises are a more modern approach to handling asynchronous operations. They represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
5.2.1 Example: Promise
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
}
fetchData().then((data) => {
console.log(data); // Output after 2 seconds: Data received
});
5.3 Async/Await
Async/await is syntactic sugar built on top of promises, allowing you to write asynchronous code that looks synchronous.
5.3.1 Example: Async/Await
async function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
}
async function displayData() {
const data = await fetchData();
console.log(data); // Output after 2 seconds: Data received
}
displayData();
In this example, the displayData
function waits for the fetchData
promise to resolve before logging the data.
6. Working with the File System
The fs
(file system) module in Node.js provides an API to interact with the file system, allowing you to read, write, update, delete, and rename files. These operations can be performed synchronously or asynchronously.
6.1 Reading and Writing Files
You can read from and write to files using the fs.readFile
and fs.writeFile
methods. Both methods have synchronous and asynchronous versions.
6.1.1 Example: Reading a File Asynchronously
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
This example reads the content of example.txt
asynchronously and logs it to the console.
6.1.2 Example: Writing to a File Asynchronously
const fs = require('fs');
fs.writeFile('example.txt', 'Hello, World!', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been written');
});
In this example, the string "Hello, World!" is written to example.txt
. If the file does not exist, it will be created.
7. NPM (Node Package Manager)
npm is the default package manager for Node.js. It allows you to install and manage libraries and tools that can be used in your Node.js applications. With npm, you can easily share and reuse code across projects.
7.1 Installing Packages
To install a package using npm, you
use the npm install
command followed by the package name.
7.1.1 Example: Installing Express
npm install express
This command installs the Express framework, a popular web application framework for Node.js.
7.2 Using Installed Packages
After installing a package, you can include it in your application using the require
function.
7.2.1 Example: Using Express
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
This example creates a basic web server using the Express framework, which responds with "Hello, World!" when accessed at http://localhost:3000/
.
8. Debugging Node.js Applications
Debugging is an essential part of the development process. Node.js provides various tools and methods for debugging, including the built-in debugger
keyword, the Node.js inspector, and third-party tools like Visual Studio Code.
8.1 Using the Debugger Keyword
The debugger
keyword can be used to set breakpoints in your code, where execution will pause, allowing you to inspect the state of the application.
8.1.1 Example: Using Debugger
let x = 5;
let y = 10;
debugger;
let z = x + y;
console.log(z);
When running this script with a debugger attached, execution will pause at the debugger
statement, allowing you to inspect variables and step through the code.
8.2 Node.js Inspector
The Node.js Inspector is a powerful tool for debugging. You can start your Node.js application with the --inspect
flag to enable debugging, and then connect to the debugger using Chrome DevTools or another compatible client.
8.2.1 Example: Starting Node.js with Inspector
node --inspect app.js
This command starts the application in debug mode, allowing you to connect to it using Chrome DevTools by navigating to chrome://inspect
in your browser.