Using Node.js as a simple web server

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Using Node.js as a simple web server

🖥️🌐📁 Serving a Single HTML Page with Images, CSS, and JavaScript 🖼️🎨📜

Hi there! 👋 Are you looking to run a simple HTTP server using Node.js? Do you want to serve a single HTML page with images, CSS, and JavaScript? I'm here to help you out! 😄

Let's first take a look at the code snippet you provided:

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(index);
}).listen(9615);

In this code, you are reading the content of index.html using fs.readFileSync. However, you are serving it as plain text with the Content-Type set to 'text/plain'. To serve it as a regular web page, we need to adjust a few things. Let's dive in! 🏊‍♂️

Step 1: Adjust Content-Type

To serve the HTML page correctly, we need to set the Content-Type header to 'text/html'. This will inform the browser that it should render the response as HTML. Let's update the code:

res.writeHead(200, {'Content-Type': 'text/html'});

Step 2: Link CSS, JavaScript, and Images

To serve CSS, JavaScript, and images, we need to include the appropriate file paths in our HTML page. Let's assume you have a CSS file called styles.css, a JavaScript file called script.js, and some images in a folder named images.

In your index.html, you should have the following lines to link these resources:

<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>

For images, you can use the following syntax:

<img src="images/example.jpg" alt="Example Image">

Make sure that the file paths in the HTML match the actual file locations.

Step 3: Sending Static Files

Now that we have included the necessary resources in our HTML page, we need to modify our server code to serve these files as well. We can achieve this using the fs module's readFileSync method, similar to what we did with index.html. Here's how you can modify the code:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
  if (req.url === '/') {
    var index = fs.readFileSync('index.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
  } else if (req.url === '/styles.css') {
    var styles = fs.readFileSync('styles.css');
    res.writeHead(200, {'Content-Type': 'text/css'});
    res.end(styles);
  } else if (req.url === '/script.js') {
    var script = fs.readFileSync('script.js');
    res.writeHead(200, {'Content-Type': 'text/javascript'});
    res.end(script);
  } else if (req.url.startsWith('/images/')) {
    var imageName = req.url.substring(8);
    try {
      var image = fs.readFileSync('images/' + imageName);
      res.writeHead(200, {'Content-Type': 'image/jpeg'}); // adjust content type based on your image type
      res.end(image);
    } catch (error) {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('Image not found');
    }
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Resource not found');
  }
}).listen(9615);

In this updated code, we added conditions to handle different URLs requested by the browser. If the URL is /, we respond with the index.html file. If it matches /styles.css, /script.js, or /images/{imageName}, we serve the corresponding files. If none of these conditions are satisfied, we return a 404 response.

You can modify the code to suit your specific file names, locations, and content types. Feel free to add more conditions if you have additional resources.

Time to Run Your Server! ⚡️

Now that we've made all the necessary adjustments, it's time to run your server! Simply execute your Node.js script using the following command:

node your-server-script.js

Remember to replace your-server-script.js with the actual filename of your server script.

Engage with Us! 🎉

I hope this guide helped you serve a single HTML page with images, CSS, and JavaScript using Node.js! 💪 If you have any questions or need further assistance, feel free to leave a comment below. We love interacting with our readers! 😊

Now it's your turn! Give it a try and share your experience with us. Did you encounter any challenges along the way? What other Node.js topics would you like us to cover in the future? Let us know in the comments section!

Happy coding! 💻✨

[Call to Action: Share this blog post on Twitter/Facebook to help others facing the same challenge!]

Image Source: Unsplash CSS Source: CodePen JavaScript Source: GitHub

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my