DEV Community

Cover image for Part 5: Building a Simple Web Server with Node.js
Dipak Ahirav
Dipak Ahirav

Posted on • Updated on

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

πŸš€ 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

Top comments (12)

Collapse
 
lirantal profile image
Liran Tal

I appreciate the education here about Node.js basics but there are also quite some security issues with the above code. It's functional, sure, but also vulnerable, so worth calling out πŸ˜…

I'm doing a lot of work to educate developers on secure coding practices in Node.js (via nodejs-security.com/) so I am sensitive to these sort of tutorials.

Collapse
 
eteimz profile image
Youdiowei Eteimorde

I really love it when the fundamentals are being taught before jumping into frameworks like express.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thanks

Collapse
 
dwivedys profile image
Saurabh Dwivedy

True

Collapse
 
gauharnawab profile image
gauharnawab

You explained with great explanation, Thankyou

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you so much @gauharnawab for your kind words and feedback! πŸ™ I'm thrilled to hear that you found the post helpful. Your support means a lot to me. If you enjoyed this post, please consider subscribing to my YouTube channel devDive with Dipak for more content. Don’t forget to share it with your friends and help spread the word. Your support helps me to continue creating valuable content. Thanks again! 😊

Collapse
 
asadsaleh profile image
AsadSaleh

Nice to not jump immediately into frameworks

Collapse
 
ubeyidah profile image
ubeyidah

try express.

Collapse
 
shifi profile image
Shifa Ur Rehman • Edited

There is a high chance if he can write a plain html http server he can do it with express too.

However this approach is much much better than using express (with some drawbacks yes). e.g. this is a module leas script. It means there is no package manager, no node_modules etc. its a plain script you can just node script.js to run with little overhead. Not to forget the immense control because of the barebones nature of this approach as well. The obvious con is performance and developer experience.

Collapse
 
snuggs profile image
Ahmid-RA

Try being a new dev again.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Join this group for more updates : FullStackLearners

Collapse
 
dipakahirav profile image
Dipak Ahirav

Next Part -> PART - 6