Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

HTTP Range Requests

Support partial content requests for streaming large files, videos, and media with efficient byte-range handling.

Basic Range Request Support

MoroJS provides built-in HTTP range request middleware for efficient streaming of large files and media content.

Enable Range Requests

typescript

1import { range } from '@morojs/moro';
2import fs from 'fs/promises';
3
4// Enable range requests
5app.use(range({
6  acceptRanges: 'bytes',
7  maxRanges: 5
8}));
9
10// Serve video with range support
11app.get('/videos/:id', async (req, res) => {
12  const videoPath = `./videos/${req.params.id}.mp4`;
13  const stats = await fs.stat(videoPath);
14  
15  // sendRange handles partial content automatically
16  res.sendRange(videoPath, stats);
17});

Range Request Features

  • • Support for HTTP Range header (bytes)
  • • Automatic partial content responses (206)
  • • Content-Range header generation
  • • Efficient streaming of large files
  • • Support for multiple ranges
  • • Video and media streaming support

Advanced Usage

Range Support for Custom Data

typescript

1import { range } from '@morojs/moro';
2
3// Range support for custom data
4app.get('/api/data', (req, res) => {
5  const data = getLargeData();
6  
7  if (req.headers.range) {
8    const range = parseRange(req.headers.range, data.length);
9    res.status(206); // Partial Content
10    res.setHeader('Content-Range', `bytes ${range.start}-${range.end}/${data.length}`);
11    res.setHeader('Accept-Ranges', 'bytes');
12    res.setHeader('Content-Length', range.end - range.start + 1);
13    return data.slice(range.start, range.end + 1);
14  }
15  
16  return data;
17});
18
19// Streaming large files
20app.get('/download/:file', async (req, res) => {
21  const filePath = `./files/${req.params.file}`;
22  const stats = await fs.stat(filePath);
23  
24  // Automatically handles range requests
25  res.sendRange(filePath, stats);
26});

Best Practices

Do

  • • Enable range requests for large files
  • • Use range requests for video streaming
  • • Set appropriate maxRanges limits
  • • Handle range errors gracefully
  • • Use Content-Range headers correctly
  • • Support resume downloads

Don't

  • • Enable range for small files
  • • Skip range validation
  • • Allow unlimited ranges
  • • Ignore range errors
  • • Use range for dynamic content
  • • Skip Content-Range headers

Related Features