Learn Node.js from scratch with this hands-on crash course. This tutorial walks you through the Node.js runtime, setting up an environment, creating an HTTP server, and understanding ES modules and Node.js core functionality.
Understand the Basics of Node.js
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It enables developers to run JavaScript on the server side. Key features of Node.js include:
- Non-blocking I/O: Efficiently handles multiple requests without waiting for operations like file or database access.
- Single-threaded architecture: Uses an event loop for high scalability.
- Versatility: Primarily used for real-time applications, APIs, and server-side scripting.
Its ecosystem, extensive library of packages, and its ability to use JavaScript for both frontend and backend make it a popular choice among developers.
prerequisites
- Familiarity with basic JavaScript, such as variables, functions, loops, and asynchronous programming (e.g., promises, async/await).
- Understanding of HTTP methods (GET, POST, PUT, DELETE), status codes, and JSON formatting.
- Installed Node.js (version 20+ recommended).
Setting Up the Environment
Set up your environment and ensure Node.js is correctly installed.
steps
- Download and install Node.js:
- Visit Node.js official website.
- Use the LTS (Long-Term Support) version for stability.
- Verify the installation:bash
node --version # v20.x.x npm --version # Ensures Node.js package manager is installed - Create a new folder for your project:bash
mkdir nodejs-tutorial cd nodejs-tutorial code . # Open the project in Visual Studio Code - Initialize Node.js project:bash
npm init -y # This creates a default package.json
Create a Basic HTTP Server with Node.js
Learn how to create an HTTP server using Node.js.
steps
- Create an
index.jsfile in your project folder. - Add the following code to create a basic server:javascript
import http from 'http'; const PORT = 5000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, Node.js!'); }); server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); }); - Run the server:bash
node index.js # Server running at http://localhost:5000/ - Test the server by navigating to
http://localhost:5000in your browser or using a tool likecurl:bashcurl http://localhost:5000 # Hello, Node.js!
Using ES Modules in Node.js
Node.js supports modern ES modules for better compatibility with frontend JavaScript. To enable ES modules, follow these steps:
steps
- Add a
"type": "module"field to yourpackage.jsonfile:json{ "name": "nodejs-tutorial", "version": "1.0.0", "type": "module", "main": "index.js" } - Modify
index.jsto use ES module syntax:javascriptimport http from 'http'; const PORT = 5000; const server = http.createServer((req, res) => { res.end('Using ES Modules!'); }); server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); }); - Restart the server:bash
node index.js # Output: Server running at http://localhost:5000/
Node.js Core Modules Overview
Node.js includes a variety of built-in modules:
- HTTP Module: Create web servers and handle requests, as seen above.
- File System (fs): Work with files.
- Example: Reading a file (make sure you pre-create an
example.txtfile in your project folder before running this code):javascriptimport { readFile } from 'fs/promises'; async function readExample() { try { const data = await readFile('./example.txt', 'utf8'); console.log(data); } catch (error) { console.error('Error reading file:', error.message); } } readExample();
- Example: Reading a file (make sure you pre-create an
- Path Module: Work with and manipulate file paths.
- Example (fixing ES module
__dirnameissue by usingimport.meta.url):javascriptimport path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const filePath = path.join(__dirname, 'folder', 'file.txt'); console.log(filePath);
- Example (fixing ES module
- OS Module: Access system-level information.
- Example:javascript
import os from 'os'; console.log(os.platform()); // e.g., 'win32'
- Example:
- Crypto Module: Perform cryptographic operations.
- Example: Generating a hash.javascript
import crypto from 'crypto'; const hash = crypto.createHash('sha256').update('password123').digest('hex'); console.log(hash);
- Example: Generating a hash.
Building and Testing Your API
steps
- Update
index.jswith a RESTful API:javascriptimport http from 'http'; const users = [ { id: 1, name: 'User1' }, { id: 2, name: 'User2' }, ]; const server = http.createServer((req, res) => { if (req.url === '/api/users' && req.method === 'GET') { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(users)); } else if (req.url === '/api/users' && req.method === 'POST') { let body = ''; req.on('data', chunk => (body += chunk)); req.on('end', () => { try { const newUser = JSON.parse(body); users.push(newUser); res.writeHead(201, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(newUser)); } catch (err) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Invalid JSON' })); } }); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Route not found'); } }); const PORT = 5000; server.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`)); - Test API endpoints using Postman or curl:bash
curl http://localhost:5000/api/users # [{"id":1,"name":"User1"},{"id":2,"name":"User2"}] - Test adding a user:bash
curl -X POST -H "Content-Type: application/json" -d '{"id":3,"name":"User3"}' http://localhost:5000/api/users # {"id":3,"name":"User3"}
Summary and Next Steps
FAQ
Can I use Node.js for real-time applications?
Yes, Node.js is highly suitable for real-time applications, especially those involving WebSockets, like chat applications or real-time collaboration tools.
How do I switch between CommonJS and ES modules in Node.js?
You can use ES modules by adding "type": "module" to your package.json. This enables import and export syntax instead of require and module.exports.
Is Node.js suitable for CPU-intensive applications?
Node.js is not ideal for heavy CPU workloads since it operates on a single-threaded event loop. For CPU-intensive tasks, you might consider using worker threads or offloading tasks to another programming language.
What are common use cases for Node.js?
Node.js is widely used for backend APIs, real-time applications like chat apps and games, microservices, static file servers, command-line tools, bots, and web scraping.