Class 20: Introduction to Backend Development & Node.js Basics
Welcome to the backend! Up until now, we've focused on the "client-side" of web development—what users see and interact with directly in their browsers. Now, we'll shift our attention to the "server-side," the powerful engine that processes data, manages databases, and serves content to the frontend.
The Role of the Backend
In the world of web development, the client-server model is fundamental.
- Client (Frontend): This is typically the web browser or a mobile application. It's responsible for presenting the user interface and sending requests to the server.
- Server (Backend): This is a powerful computer program that listens for requests from clients, processes them, and sends back responses.
The backend is responsible for several critical tasks:
- Data Storage: Storing and managing all the application's data in databases (e.g., user profiles, product information, blog posts).
- Business Logic: Implementing the core rules and operations of the application (e.g., processing orders, calculating prices, user authentication).
- API (Application Programming Interface): Providing a set of rules and definitions for how clients can communicate with the server to request or send data.
- Authentication & Authorization: Verifying user identities and ensuring they have the necessary permissions to access specific resources.
- Security: Protecting data and systems from unauthorized access and malicious attacks.
Introduction to Node.js
Traditionally, backend development involved languages like Java, Python, Ruby, or PHP. Node.js changed the game by allowing developers to use JavaScript on the server-side.
- What is Node.js? Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a web browser. It's built on Chrome's V8 JavaScript engine.
-
Why Node.js for backend development?
- Asynchronous & Non-blocking I/O: Node.js handles operations like reading files or making database queries in a non-blocking way. This means it can process other requests while waiting for an I/O operation to complete, making it very efficient for applications with many concurrent connections.
- Single-threaded Event Loop: Despite being single-threaded, Node.js uses an event loop mechanism that allows it to perform non-blocking I/O operations, making it highly scalable.
- Unified Language: Using JavaScript for both frontend and backend (full-stack JavaScript) simplifies development, allows for code sharing, and reduces context switching for developers.
-
Node.js Use Cases:
- Building RESTful APIs (Application Programming Interfaces)
- Real-time applications (chat apps, live dashboards)
- Microservices
- Streaming applications
- Command-line tools
Node Package Manager (npm)
npm
(Node Package Manager) is the default package
manager for Node.js and the world's largest software registry.
It's used for installing, managing, and sharing reusable code
packages (libraries) for your Node.js projects.
Basic npm Commands:
-
npm init
:Initializes a new Node.js project and creates a
package.json
file. This file stores metadata about your project (name, version, description, entry point) and lists its dependencies.# In your project directory npm init -y # The -y flag answers "yes" to all prompts, creating a default package.json
After running this, you'll see a
package.json
file similar to this:{ "name": "my-node-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
-
npm install <package>
:Installs a specific package and adds it to your project's dependencies in
package.json
. The package files are downloaded into anode_modules
folder.# Install a package (e.g., express) as a production dependency npm install express # Install a package as a development dependency (e.g., for testing) npm install jest --save-dev # or npm install jest -D
After installing
express
, yourpackage.json
will be updated:{ "name": "my-node-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2" } }
You'll also notice a
package-lock.json
file. This file records the exact versions of every package installed, ensuring that your project dependencies are consistent across different environments and installations. -
npm install
(without arguments):Installs all dependencies listed in
package.json
. This is what you'll run when you clone a new Node.js project from a repository. -
npm run <script_name>
:Executes custom scripts defined in the
"scripts"
section of yourpackage.json
.# Example package.json script "scripts": { "start": "node index.js", "dev": "nodemon index.js" } # To run the 'start' script npm run start # or simply npm start # (for 'start' and 'test' scripts, 'run' is optional)
Basic Node.js Modules
Node.js has a rich set of built-in modules that provide core
functionalities without needing to install external packages.
You import them using the require()
function
(CommonJS syntax, common in Node.js backend) or
import
(ES Modules, gaining popularity).
-
http
module:Used to create HTTP servers and clients. It's the foundation for building web applications in Node.js.
const http = require('http');
-
fs
module (File System):Provides methods for interacting with the file system, such as reading files, writing files, creating directories, etc.
const fs = require('fs'); // Example: Reading a file asynchronously fs.readFile('myfile.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });
-
path
module:Provides utilities for working with file and directory paths, regardless of the operating system.
const path = require('path'); const filePath = path.join(__dirname, 'data', 'users.json'); console.log(filePath); // e.g., /Users/youruser/project/data/users.json
-
os
module (Operating System):Provides operating system-related utility methods and properties.
const os = require('os'); console.log(`Operating System: ${os.platform()}`); console.log(`Free Memory: ${os.freemem() / (1024 * 1024)} MB`);
Building a Simple "Hello World" HTTP Server
Let's put some of these concepts into practice by creating a
very basic web server using Node.js's built-in
http
module.
Create a file named server.js
(or
index.js
) in your project directory:
// server.js
const http = require('http'); // Import the built-in http module
const hostname = '127.0.0.1'; // Localhost IP address
const port = 3000; // Port number for our server to listen on
// Create an HTTP server
const server = http.createServer((req, res) => {
// req is the request object from the client
// res is the response object we send back to the client
// Set the response HTTP header with a status code and content type
res.statusCode = 200; // 200 OK
res.setHeader('Content-Type', 'text/plain'); // Tell the client it's plain text
// Basic routing logic
if (req.url === '/') {
res.end('Hello, World! This is the homepage.');
} else if (req.url === '/about') {
res.end('This is the about page. Learn more about us!');
} else {
res.statusCode = 404; // Not Found
res.end('Page Not Found');
}
});
// Start the server and listen for incoming requests
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
console.log('You can access:');
console.log(`- http://localhost:${port}/`);
console.log(`- http://localhost:${port}/about`);
console.log(`- http://localhost:${port}/some-other-path`);
});
How to Run This Server:
- Make sure you have Node.js installed.
- Open your terminal or command prompt.
-
Navigate to the directory where you saved
server.js
. -
Run the command:
node server.js
-
You should see the message:
Server running at http://127.0.0.1:3000/
-
Open your web browser and navigate to:
- http://localhost:3000/ (You should see "Hello, World! This is the homepage.")
- http://localhost:3000/about (You should see "This is the about page. Learn more about us!")
- http://localhost:3000/some-other-path (You should see "Page Not Found")
-
To stop the server, press
Ctrl + C
in your terminal.
This simple example demonstrates how Node.js can act as a web
server, listen for requests, and send responses. While the
http
module is powerful, directly managing routing
and complex request handling can become cumbersome. This is
where frameworks like Express.js come in, which we'll explore in
the next class!