Serving Static Files with Node.js

Node.js can be used as a simple web server to serve static files such as HTML, CSS, and JavaScript. In this tutorial, we will explore how to create a basic web server using Node.js to serve these types of files.

Introduction to HTTP Servers

An HTTP server is a program that listens for incoming requests from clients, such as web browsers, and responds with the requested resources. Node.js provides a built-in http module that can be used to create an HTTP server.

Creating a Basic Web Server

To create a basic web server using Node.js, you will need to use the http module and the fs module to read files from the file system. Here is a simple example of how you can create a web server:

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

http.createServer((req, res) => {
  // Read the requested file
  const filename = './index.html';
  fs.readFile(filename, (err, data) => {
    if (err) {
      // If there is an error, send a 404 response
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('File not found');
    } else {
      // Send the file contents as the response body
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(data);
    }
  });
}).listen(3000, () => {
  console.log('Server running on port 3000');
});

This example creates a web server that listens for incoming requests on port 3000. When a request is received, it reads the contents of the index.html file and sends it as the response body.

Serving Multiple File Types

To serve multiple file types, such as CSS and JavaScript files, you will need to modify the example above to handle different file extensions. One way to do this is by using a switch statement or an object that maps file extensions to content types:

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

const contentTypesByExtension = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'application/javascript'
};

http.createServer((req, res) => {
  const url = req.url;
  const filename = path.join(__dirname, url);

  fs.exists(filename, (exists) => {
    if (!exists) {
      // If the file does not exist, send a 404 response
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('File not found');
    } else {
      const ext = path.extname(filename);
      const contentType = contentTypesByExtension[ext];
      fs.readFile(filename, (err, data) => {
        if (err) {
          // If there is an error reading the file, send a 500 response
          res.writeHead(500, {'Content-Type': 'text/plain'});
          res.end('Error reading file');
        } else {
          // Send the file contents as the response body with the correct content type
          res.writeHead(200, {'Content-Type': contentType});
          res.end(data);
        }
      });
    }
  });
}).listen(3000, () => {
  console.log('Server running on port 3000');
});

This example uses an object to map file extensions to content types and sends the correct content type header based on the requested file’s extension.

Serving Static Files with Connect

Another way to serve static files is by using a library like Connect. Connect provides a simple way to create a web server that can handle multiple routes and middleware functions:

const connect = require('connect');
const http = require('http');

const app = connect();

app.use(connect.static(__dirname));

http.createServer(app).listen(3000, () => {
  console.log('Server running on port 3000');
});

This example creates a web server that serves static files from the current directory using Connect’s static middleware.

Conclusion

In this tutorial, we explored how to create a basic web server using Node.js to serve static files. We also looked at how to handle different file extensions and content types. Additionally, we introduced the use of libraries like Connect to simplify the process of serving static files. With these examples, you should be able to create your own simple web servers to serve static files.

Leave a Reply

Your email address will not be published. Required fields are marked *