javascript-today

Node.js

Node.js Development

Learn how to use JavaScript outside the browser with Node.js.

What You’ll Learn

This section covers Node.js-specific development:

Prerequisites

Complete the JavaScript fundamentals section first. Understanding of:

Getting Started

Make sure you have Node.js installed before starting these tutorials.

What is NodeJS

NodeJS is a runtime environment that allows you to run JavaScript on the server-side, outside of a web browser. It was created in 2009 by Ryan Dahl and is built on Chrome’s V8 JavaScript engine. Why NodeJS? Before NodeJS, JavaScript could only run in web browsers. NodeJS changed that by providing: Server-side JavaScript: Write backend code in the same language as your frontend Fast execution: Built on Chrome’s V8 engine (compiled to machine code) Non-blocking I/O: Handle thousands of concurrent connections efficiently NPM ecosystem: Access to over 2 million packages What Can You Build?

Setting Up NodeJS

Getting started with NodeJS is straightforward. This tutorial will walk you through installation, verification, and running your first Node script. Installing NodeJS Option 1: Download from Official Website (Easiest) Visit nodejs.org Download the LTS version (Long Term Support) More stable for production use Gets security updates for longer Run the installer and follow the prompts Restart your terminal/command prompt Option 2: Using a Version Manager (Recommended for Developers) On Mac/Linux (using nvm):

Modules and Require

NodeJS uses a module system to organize code into reusable pieces. Understanding modules is essential for writing maintainable Node applications. What Are Modules? A module is simply a JavaScript file that exports functionality for other files to use. NodeJS uses the CommonJS module system by default. // math.js - a simple module function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } // Export functions module.

NPM Basics

NPM (Node Package Manager) is the world’s largest software registry with over 2 million packages. It comes bundled with NodeJS and is essential for modern JavaScript development. What is NPM? NPM serves two main purposes: Package manager: Install and manage third-party libraries Script runner: Run build scripts, tests, and development servers Every NodeJS project uses a package.json file to manage dependencies and scripts. Creating a New Project Initialize a new Node project:

File System Operations

One of NodeJS’s most powerful features is direct access to the file system. The built-in fs module lets you read, write, delete, and manipulate files and directories. The fs Module const fs = require('fs'); The fs module has two styles of APIs: Synchronous (blocking) - ends with Sync Asynchronous (non-blocking) - callback or promise-based Reading Files Synchronous (Blocking) const fs = require('fs'); // Read entire file const data = fs.readFileSync('data.txt', 'utf8'); console.

Creating HTTP Servers

NodeJS was designed for building network applications, especially web servers. The built-in http module makes it easy to create HTTP servers without any external dependencies. Your First HTTP Server const http = require('http'); // Create server const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, World!'); }); // Start listening server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); }); Save as server.js and run: node server.js Visit http://localhost:3000 in your browser!

Express Framework Basics

Express is the most popular NodeJS web framework. It simplifies building web servers and APIs by providing a clean, minimal interface on top of the raw http module. Why Express? Express makes web development easier: Task Raw HTTP Express Routing Manual if/else app.get('/path', ...) JSON parsing Manual chunks Built-in Static files Manual fs.readFile express.static() Middleware Manual Built-in system Error handling Manual try/catch Centralized Installing Express # Create new project mkdir my-app cd my-app npm init -y # Install Express npm install express Your First Express Server // server.

Express Routing and Middleware

Express routing is how you define endpoints (URLs) that your application responds to. As your app grows, good routing organization becomes essential. Route Methods Express supports all HTTP methods: const express = require('express'); const app = express(); // GET request app.get('/users', (req, res) => { res.send('Get all users'); }); // POST request app.post('/users', (req, res) => { res.send('Create a user'); }); // PUT request app.put('/users/:id', (req, res) => { res.send(`Update user ${req.

Express Middleware

Middleware functions are the backbone of Express applications. They have access to the request and response objects and can modify them, end the request, or pass control to the next middleware. What is Middleware? Middleware is a function that executes between receiving a request and sending a response: Request → Middleware 1 → Middleware 2 → Route Handler → Response Basic middleware structure: function myMiddleware(req, res, next) { // Do something with req or res console.

Serving Static Files

Static files are assets that don’t change - HTML, CSS, JavaScript, images, fonts, PDFs, etc. Express makes serving these files simple with the built-in express.static() middleware. Basic Static File Serving Serve files from a directory: const express = require('express'); const app = express(); // Serve files from 'public' directory app.use(express.static('public')); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); Project structure: project/ ├── server.js └── public/ ├── index.html ├── about.html ├── css/ │ └── style.

Form Handling

Forms are how users send data to your server. Express makes it easy to receive and process form data from HTML forms, whether it’s login credentials, search queries, or file uploads. Form Basics HTML Form <form action="/submit" method="POST"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button type="submit">Login</button> </form> Express Handler const express = require('express'); const app = express(); // Required to parse form data app.use(express.urlencoded({ extended: true })); app.post('/submit', (req, res) => { console.

Environment Variables

Environment variables allow you to configure your application differently for development, testing, and production without changing code. They’re essential for keeping secrets safe. What are Environment Variables? Variables set outside your code that your application can access: // Access environment variables console.log(process.env.NODE_ENV); // "development" or "production" console.log(process.env.PORT); // "3000" console.log(process.env.DATABASE_URL); Common uses: API keys and secrets Database connection strings Port numbers Environment mode (dev/prod) Feature flags Using process.env Built into Node.

REST API Basics

REST (Representational State Transfer) is an architectural style for designing APIs. Most modern web APIs follow REST principles to create predictable, easy-to-use interfaces. What is REST? REST uses HTTP methods to perform operations on resources: GET /api/users → Get all users GET /api/users/1 → Get user with ID 1 POST /api/users → Create new user PUT /api/users/1 → Update user 1 DELETE /api/users/1 → Delete user 1 Key concepts: Resources (users, posts, products) HTTP methods (GET, POST, PUT, DELETE) Status codes (200, 404, 500) Stateless (each request is independent) HTTP Methods GET - Retrieve Data const express = require('express'); const app = express(); // Get all items app.

Building a CRUD API

Let’s build a complete, production-ready CRUD API for managing a todo list. This tutorial brings together everything you’ve learned about Express, REST principles, and best practices. Project Setup Create a new project: mkdir todo-api cd todo-api npm init -y npm install express dotenv npm install nodemon --save-dev package.json: { "scripts": { "start": "node server.js", "dev": "nodemon server.js" } } .env: PORT=3000 NODE_ENV=development Project Structure todo-api/ ├── server.js # Entry point ├── config/ │ └── config.

Error Handling Patterns

Proper error handling makes your application reliable and helps debug issues quickly. Express provides several ways to handle errors gracefully. Basic Error Handling Try-Catch for Synchronous Errors const express = require('express'); const app = express(); app.get('/api/users/:id', (req, res) => { try { const id = parseInt(req.params.id); if (isNaN(id)) { throw new Error('Invalid user ID'); } // Simulate error if (id > 100) { throw new Error('User not found'); } res.json({ id, name: 'User' }); } catch (error) { res.