1

Personal Introduction: Hi, to everyone im new to backend technology so I premtively give my apologises for being imprecise or for using bad terminology.

Brief Description of my small project So, the image below is a brief description of the functionality I want to implement for my small project, let me resume the diagram with my words. Ideally, I want to build an application that:

  1. listens to a local folder with node/express.
  2. gets the list of files from the chosen folder .
  3. "streams" the files in parallel(or sequetially if impossible) with something like an "fs.createReadStream()" or any other method suitable for this task.
  4. Gets the src attribute of each file and displays multiple <video/> on one single page.

Simple illustration of my ideal project

Additional details I'm using a combination of React+Vite, Node+express currently, but that shouldn't change anything compared to a native React project.

My problem

  1. I'm currently lacking the necessary information to understand multiple file streams from the backend.
  2. I'm unable to give the "src" attribute dynamically on the front-end

My Scripts

--THIS IS THE SERVER "server.cjs"

const express = require("express");
const fs = require('fs');
const PORT = process.env.PORT || 8001;

const app = express();


app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});


app.get('/api', (req, res) => {
  res.json({name : "YEAAAA"})
})

app.get('/vid', (req,res) => {
  fs.readdir('./', 
    { withFileTypes: true },
    (err, files) => {
    if (err)
      res.send(err);
    else {
        res.send(files);
    }
  })
})

//HERE I STRUGGLE--------------------------------------------------
/*1. refers to the "read file in directory" process, in this case the read happens only when the pages reload I believe, the "contnuous update" doesn't concern me for now.
*/
/*2. refers to the actual stream, I found this snippet online, I understand the concept of sending mere bytes (BLOBs If I'm not mistaken) to the front end but I haven't wrote a single line of this except for changing the paths, the snippet works but only with one video because I don't really know how send multiple steams
*/
//1.----------------------------------
app.get('/video', function(req, res) {
  const pPath = '../../filse';
  fs.readdir(pPath, 
  { withFileTypes: true },
  (err, files) => {  //<---"files"*
  if (err)
    res.send(err);
  else {
    //res.send(files);
//end 1.-------------------------------
//2.-----------------------------------
    const path ='../../filse/abc.mp4';  /*<--- my local fixed path, want to replace "abc.mp4 with "files.name"* to make all of this a mutliple stream but of course it cannot work like that*/
    console.log(path);
    const stat = fs.statSync(path)
    const fileSize = stat.size
    const range = req.headers.range
    
    if (range) {
    const parts = range.replace(/bytes=/, "").split("-")
    const start = parseInt(parts[0], 10)
    const end = parts[1]
    ? parseInt(parts[1], 10)
    : fileSize-1
    
    const chunksize = (end-start)+1
    const file = fs.createReadStream(path, {start, end})
    const head = {
    'Content-Range': `bytes ${start}-${end}/${fileSize}`,
    'Accept-Ranges': 'bytes',
    'Content-Length': chunksize,
    'Content-Type': 'video/mp4',
    }
    
    res.writeHead(206, head)
    file.pipe(res)
    } else {
    const head = {
    'Content-Length': fileSize,
    'Content-Type': 'video/mp4',
    }
    res.writeHead(200, head)
    fs.createReadStream(path).pipe(res)  /*<--- this is the steam but I need to steam for each video in file folder*/
    }}}
  );
  //end 2.---------------------------------
});

On the other side we have the React application

//Viddz.jsx
import {React , useState , useEffect} from "react"
import "./App.css"

export default function Viddz() {

  const [data, setData] = useState();

    const getVideoData = () => {
      const response = fetch(
        "http://localhost:8001/video"
      ).then((response) => response.json());
        
      setData(response);
    };
   

    useEffect(() => {
      getVideoData();
    }, []);

    if (data != null) {
      return(
        <div className="video-files">
          <video width="750" height="500" controls >
            <source src="http://localhost:8001/video/" type="video/mp4"/> /*<--- HERE I WANT TO MAKE THE SRC ATTRIBUTE DYNAMIC, I dont really know if I should use a .map or something else once the backend is set correctly*/
          </video>
        </div>
      )
    }
}

For now this is everything, again, I apologise if I lack the correct vocaboulary, I hope the diagram is enough self explanatory.

You don't have to rewrite the snippets, at least I need to know the right tools/knowledge/resources to pull of a "One page multiple video streams" project, I don't really know where to look at or how to ask the right questions on Google so I hope for someone who can redirect me on the right path.

Thank you.

I tried to change the snippets of code illustrated in the details: In "server.cjs" with an "files.foreach(file => {..}" before the 2. snippet but that cannot simply work like that. I am expecting to deliver multiple video streams from backend node/express to my single page app and render the <video/> boxes for each file in my local folder. Everything should be on localhost, this should be very amateur for now but I just require the "dynamicity" from both front and backend.

schizoSan
  • 11
  • 1

0 Answers0