Creating a Static File Server with Node.js

In this tutorial, we will explore how to create a simple static file server using Node.js. A static file server is a type of server that serves files from a directory without modifying them. This can be useful for serving static websites, hosting files, or testing web applications.

Introduction to HTTP and File Servers

Before diving into the code, let’s understand how HTTP works. When you access a website, your browser sends an HTTP request to the server, which responds with the requested file. In our case, we want to create a server that serves static files from a directory.

Using Ready-to-Use Tools

There are several ready-to-use tools available for creating a static file server with Node.js. One popular option is http-server, which can be installed using npm:

npm install http-server -g

Once installed, you can start the server by navigating to the directory containing your files and running:

http-server -o .

This will start a server that serves files from the current directory. You can access the files by visiting http://localhost:8080 in your browser.

Creating a Custom Static File Server

If you want more control over your server or prefer to write custom code, you can create a static file server using Node.js’s built-in http module. Here’s an example:

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

const port = 8080;

http.createServer((req, res) => {
  const filePath = `.${req.url}`;
  if (filePath === './') {
    fs.readFile('./index.html', (err, data) => {
      if (err) {
        res.writeHead(500);
        res.end('Error reading file');
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  } else {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404);
        res.end('File not found');
      } else {
        const ext = path.extname(filePath);
        let contentType;
        switch (ext) {
          case '.js':
            contentType = 'text/javascript';
            break;
          case '.css':
            contentType = 'text/css';
            break;
          case '.jpg':
            contentType = 'image/jpeg';
            break;
          default:
            contentType = 'text/plain';
        }
        res.writeHead(200, { 'Content-Type': contentType });
        res.end(data);
      }
    });
  }
}).listen(port, () => {
  console.log(`Server running on port ${port}`);
});

This code creates a server that serves files from the current directory. It uses the fs module to read files and the path module to determine the file extension.

Handling CORS

If you plan to access your server from an external domain, you’ll need to handle CORS (Cross-Origin Resource Sharing). You can do this by setting the following headers:

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);

Using Express.js

If you prefer to use a framework like Express.js, you can create a static file server using the serve-static middleware:

const express = require('express');
const serveStatic = require('serve-static');

const app = express();
app.use(serveStatic('./'));

const port = 8080;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

This code creates an Express.js app that serves files from the current directory using the serve-static middleware.

Conclusion

In this tutorial, we’ve explored how to create a static file server with Node.js. We’ve covered ready-to-use tools like http-server, custom code using the http module, and frameworks like Express.js. Whether you’re hosting a static website or testing web applications, a static file server is an essential tool for any developer.

Leave a Reply

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