Developer Guides

Node.js Tutorial: Server-Side JavaScript Crash Course

Learn Node.js from scratch with this hands-on crash course. Create an HTTP server, understand ES modules, and dive into core modules.

5 min read

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

  1. Download and install Node.js:
  2. Verify the installation:
    bash
    node --version # v20.x.x
    npm --version  # Ensures Node.js package manager is installed
  3. Create a new folder for your project:
    bash
    mkdir nodejs-tutorial
    cd nodejs-tutorial
    code . # Open the project in Visual Studio Code
  4. 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

  1. Create an index.js file in your project folder.
  2. 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}/`);
    });
  3. Run the server:
    bash
    node index.js
    # Server running at http://localhost:5000/
  4. Test the server by navigating to http://localhost:5000 in your browser or using a tool like curl:
    bash
    curl 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

  1. Add a "type": "module" field to your package.json file:
    json
    {
      "name": "nodejs-tutorial",
      "version": "1.0.0",
      "type": "module",
      "main": "index.js"
    }
  2. Modify index.js to use ES module syntax:
    javascript
    import 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}/`);
    });
  3. 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:

  1. HTTP Module: Create web servers and handle requests, as seen above.
  2. File System (fs): Work with files.
    • Example: Reading a file (make sure you pre-create an example.txt file in your project folder before running this code):
      javascript
      import { 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();
  3. Path Module: Work with and manipulate file paths.
    • Example (fixing ES module __dirname issue by using import.meta.url):
      javascript
      import 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);
  4. OS Module: Access system-level information.
    • Example:
      javascript
      import os from 'os';
      console.log(os.platform()); // e.g., 'win32'
  5. 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);

Building and Testing Your API

steps

  1. Update index.js with a RESTful API:
    javascript
    import 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}`));
  2. Test API endpoints using Postman or curl:
    bash
    curl http://localhost:5000/api/users
    # [{"id":1,"name":"User1"},{"id":2,"name":"User2"}]
  3. 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.