Part 5: Building a Simple Web Server with Node.js

Dipak Ahirav - May 4 - - Dev Community

๐Ÿš€ Check Out My YouTube Channel! ๐Ÿš€

Hi everyone! If you enjoy my content here on Dev.to, please consider subscribing to my YouTube channel devDive with Dipak. I post practical full-stack development videos that complement my blog posts. Your support means a lot!

In the previous articles, we explored Node.js fundamentals, setting up your environment, and how to work with Node.js modules. Now, we're going to put that knowledge into practice by building a simple web server. This practical application will consolidate your understanding and showcase the power of Node.js in handling web requests.

Step 1: Review of the HTTP Module

We briefly touched on the http module in our discussion about built-in modules. It's a core Node.js module used to create HTTP servers. Here's a quick recap:

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
Enter fullscreen mode Exit fullscreen mode

Step 2: Expanding Our Server

Now, letโ€™s enhance our server by handling different routes and serving static files.

Handling Routes

We can handle different routes by checking the URL in the request object. Letโ€™s add a simple routing mechanism:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('<h1>Welcome to Our Home Page</h1>');
  } else if (req.url === '/about') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('<h1>About Us</h1>');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/html');
    res.end('<h1>Page Not Found</h1>');
  }
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
Enter fullscreen mode Exit fullscreen mode
Serving Static Files

To serve static files like HTML, CSS, and JavaScript, you can create a function to read file contents and send them in the response:

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);

  const ext = path.extname(filePath);
  let contentType = 'text/html';
  switch (ext) {
    case '.css':
      contentType = 'text/css';
      break;
    case '.js':
      contentType = 'text/javascript';
      break;
    case '.json':
      contentType = 'application/json';
      break;
    // Add more cases for other file types if needed
  }

  fs.readFile(filePath, (err, content) => {
    if (err) {
      if (err.code === 'ENOENT') {
        // Page not found
        fs.readFile(path.join(__dirname, 'public', '404.html'), (err, content) => {
          res.writeHead(404, { 'Content-Type': 'text/html' });
          res.end(content, 'utf-8');
        });
      } else {
        // Some server error
        res.writeHead(500);
        res.end(`Server Error: ${err.code}`);
      }
    } else {
      // Success
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
Enter fullscreen mode Exit fullscreen mode

Support My Work

If you enjoy my content and want to support my work, consider buying me a coffee! Your support helps me continue creating valuable content for the developer community.

Buy Me a Coffee

Conclusion

Building a web server with Node.js is straightforward thanks to its powerful core modules. By handling routes and serving static files, you've taken significant steps toward developing full-fledged web applications. In the next part of our series, we'll explore how to integrate external libraries and frameworks to further enhance your server's capabilities.

Stay tuned for more advanced Node.js development techniques!

Series Index

Part Title Link
1 Ditch Passwords: Add Facial Recognition to Your Website with FACEIO Read
2 The Ultimate Git Command Cheatsheet Read
3 Top 12 JavaScript Resources for Learning and Mastery Read
4 Angular vs. React: A Comprehensive Comparison Read
5 Top 10 JavaScript Best Practices for Writing Clean Code Read
6 Top 20 JavaScript Tricks and Tips for Every Developer ๐Ÿš€ Read
7 8 Exciting New JavaScript Concepts You Need to Know Read
8 Top 7 Tips for Managing State in JavaScript Applications Read
9 ๐Ÿ”’ Essential Node.js Security Best Practices Read
10 10 Best Practices for Optimizing Angular Performance Read
11 Top 10 React Performance Optimization Techniques Read
12 Top 15 JavaScript Projects to Boost Your Portfolio Read
13 6 Repositories To Master Node.js Read
14 Best 6 Repositories To Master Next.js Read
15 Top 5 JavaScript Libraries for Building Interactive UI Read
16 Top 3 JavaScript Concepts Every Developer Should Know Read
17 20 Ways to Improve Node.js Performance at Scale Read
18 Boost Your Node.js App Performance with Compression Middleware Read
19 Understanding Dijkstra's Algorithm: A Step-by-Step Guide Read
20 Understanding NPM and NVM: Essential Tools for Node.js Development Read
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player