How can I implement file streaming in an Express js server

0 votes

How can I implement file streaming in an Express.js server?

I'm looking to implement file streaming in an Express.js server to handle large files efficiently without loading them fully into memory. I’d like to understand the process and the best practices, especially for streaming video or large data files to clients. What’s the right way to set up file streaming in an Express.js application?

Oct 28 in Web Development by Nidhi
• 2,660 points
84 views

1 answer to this question.

0 votes

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}`);
});
answered Nov 13 by kavya

Related Questions In Web Development

0 votes
1 answer
0 votes
1 answer

How can I create a rate limiter middleware for an Express.js API?

const express = require('express'); const rateLimit = require('express-rate-limit'); const ...READ MORE

answered Oct 28 in Web Development by kavya
77 views
0 votes
0 answers

How can I debounce an input field in React?

Oct 10 in Web Development by anonymous
• 2,660 points
121 views
0 votes
0 answers

How to upload a file to api server in node js?

How to upload a file to api ...READ MORE

Oct 14 in Web Development by anonymous
• 2,660 points
67 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
1,922 views
0 votes
1 answer

Hyperledger Sawtooth vs Quorum in concurrency and speed Ask

Summary: Both should provide similar reliability of ...READ MORE

answered Sep 26, 2018 in IoT (Internet of Things) by Upasana
• 8,620 points
1,451 views
+1 vote
1 answer

Protocols used in a distributed/dlt system for the nodes to establish communication

yes all are over TCP/IP connections secured ...READ MORE

answered Aug 6, 2018 in Blockchain by aryya
• 7,460 points
1,427 views
0 votes
1 answer

How can I handle CORS issues in an Express.js backend?

CORS(Cross-Origin Resource Sharing ) is a security  ...READ MORE

answered Oct 25 in Web Development by kavya
64 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP