Node.js HTTP Static File Streaming

1.2.1 · active · verified Sun Apr 19

The `send` library provides a low-level utility for streaming static files directly from the file system in Node.js, specifically designed for HTTP responses. It expertly handles features like partial content responses via Range headers, conditional-GET negotiation using If-Match, If-None-Match, If-Modified-Since, and ETag generation. It offers granular control over aspects such as caching (Cache-Control, maxAge, immutable), dotfile handling, and automatic file extension resolution. While a `1.x.x` series exists (up to 1.2.1), the most recent stable release is currently `0.19.2`, indicating a somewhat unconventional release cadence or a focus shift. It is a foundational component often leveraged by higher-level static file serving middleware like `serve-static` within web frameworks.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to set up a basic Node.js HTTP server using `send` to serve static files from a 'public' directory, handling errors and directory requests.

import http from 'http';
import path from 'path';
import send from 'send';
import { fileURLToPath } from 'url';

// In an ESM module, __dirname is not directly available. Recreate it.
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Create a simple HTTP server
const server = http.createServer((req, res) => {
  const filePath = path.join(__dirname, 'public', req.url || 'index.html');
  
  // Basic example of creating a public directory and a file
  // For a real application, ensure 'public' directory exists with files
  // or adjust `root` option accordingly.
  // Example: echo '<h1>Hello from send!</h1>' > public/index.html

  send(req, req.url || '/', { root: path.join(__dirname, 'public') })
    .on('error', (err) => {
      if (err.statusCode === 404) {
        res.statusCode = 404;
        res.end('File not found');
      } else {
        res.statusCode = 500;
        res.end('Internal Server Error: ' + err.message);
      }
    })
    .on('directory', () => {
      // Redirect or serve index.html for directory requests if desired
      res.statusCode = 301;
      res.setHeader('Location', req.url + '/index.html');
      res.end('Redirecting to index.html');
    })
    .on('end', () => {
      console.log(`Served: ${req.url}`);
    })
    .pipe(res);
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`);
  console.log(`Try http://localhost:${PORT}/index.html (create 'public/index.html' first)`);
});

view raw JSON →