A Node.js server that allows streaming of torrent files via HTTP, built with WebTorrent and Express. The server handles torrent downloads and provides video streaming capabilities with support for range requests.
- Torrent metadata fetching
- Video streaming with range request support
- Automatic torrent cleanup
- Error handling with retry mechanism
- Resource management for active torrents and streams
- Graceful shutdown handling
- Node.js (version 14 or higher)
- npm or yarn package manager
- Clone the repository
- Install dependencies:
npm installRequired dependencies:
- webtorrent
- express
- cors
The server uses several configuration constants that can be modified in the code:
const MAX_RETRIES = 3 // Maximum number of retry attempts for adding torrents
const RETRY_DELAY = 5000 // Delay between retry attempts (in milliseconds)
const CLEANUP_DELAY = 120000 // Delay before cleaning up inactive torrents (2 minutes)GET /add/:magnet
Adds a new torrent to the server. The magnet URI should be URL encoded.
Parameters:
magnet: URL-encoded magnet link
Response:
{
"files": [
{
"name": "filename.mp4",
"length": 1234567
}
]
}GET /stream/:infoHash/:fileName
Streams a file from the specified torrent.
Parameters:
infoHash: Torrent info hashfileName: URL-encoded name of the file to stream
Supports range requests for seeking in video players.
The server implements several error handling mechanisms:
- Retry logic for failed torrent additions
- Stream error handling
- Client disconnect handling
- Resource cleanup for inactive torrents
The server tracks:
- Active torrents
- Active streams
- Retry attempts
Resources are automatically cleaned up when:
- Streams end or encounter errors
- Clients disconnect
- Torrents become inactive
- Add a torrent:
curl "http://localhost:3000/add/magnet%3A%3Fxt%3Durn%3Abtih%3AINFOHASH..."- Stream a file:
curl "http://localhost:3000/stream/INFOHASH/video.mp4"Start the server:
node server.jsThe server will listen on port 3000 by default.
- The server includes built-in cleanup mechanisms to prevent resource leaks
- Torrents are automatically destroyed when inactive
- The server handles graceful shutdown on SIGINT (Ctrl+C)
- Streams only video files as MP4 format
- Torrents are stored temporarily and cleaned up after inactivity
- Maximum web connections per torrent is set to 30