To carry out this file streaming scheme in an Express.js server, we utilize Node.js's fs.createReadStream() methods. This technique opens up large files sequentially, enabling the efficient transfer of data and allowing users to start using the content without waiting for a full download
// 1. Set up the necessary modules:
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
// Port configuration
const PORT = 3000;
// 2. Create a route to handle file streaming:
app.get('/stream/:filename', (req, res) => {
const filePath = path.join(__dirname, 'files', req.params.filename);
// Check if the file exists
if (!fs.existsSync(filePath)) {
return res.status(404).send('File not found');
}
// Get file stats (size, etc.)
const stat = fs.statSync(filePath);
// Set response headers for streaming
res.writeHead(200, {
'Content-Type': 'video/mp4', // Adjust this for different file types
'Content-Length': stat.size,
});
// Create a read stream from the file
const readStream = fs.createReadStream(filePath);
// Pipe the read stream to the response object
readStream.pipe(res);
});
// 3. Example endpoints to demonstrate the streaming
// This will serve different types of files from the 'files' directory.
// Make sure to have example files in the 'files' directory like 'video.mp4' and 'audio.mp3'.
app.get('/', (req, res) => {
res.send(`
<h1>File Streaming Server</h1>
<p>Use the following routes to stream files:</p>
<ul>
<li><a href="/stream/video.mp4">Stream video.mp4</a></li>
<li><a href="/stream/audio.mp3">Stream audio.mp3</a></li>
</ul>
`);
});
// 4. Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});