Use Node's express.static method to read and serve files from a specified

I am currently working on a Video Portal Project that involves organizing videos into different folders on the server. Utilizing nodejs technology, my goal is to create a function that can access and display all video content within a specific folder. At the moment, the code I have only serves a single file rather than an entire folder. I would greatly appreciate any contributions or suggestions to help me achieve this functionality. Thank you.

  let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');

let fs = require('fs');
var ejs=require('ejs');
let port = process.env.PORT || 4000;
let videosPath = './videos/';

let app = express();

// Set view engine
app.set('view engine', 'ejs');
app.set('views', path.join( __dirname, 'views'));

// Using body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// Route to handle fetching videos from a specific folder
app.get('/videos/:id',function(req,res){

    fs.readdir(`./videos/${req.params.id}`, (err, files) => {
       console.log(files);
       res.render('pages/index',{videos:files,cateogry_id:req.params.id});
    });

});

// Default route
app.get('/',function(req,res){
    res.render('index');
});

app.listen(port, function(){
    console.log("Server running on port 4000");
});

Answer №1

Utilize EJS for efficient template rendering :

For a comprehensive tutorial on how to use EJS for templating, check out this helpful link.

To get started, create a 'views' folder within the main directory of your project. This is where you'll store your EJS pages for rendering.

Next, create an index.ejs file inside the projectName/views/ directory.

Within your index.ejs file, input the following:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</head>
<body>

  <h3><%=videos.length+'total videos'%><h3>

  <div class="row">

  <% videos.forEach(function(video)){ %>
       <div class="col-lg-4 my-2">
         <video width="320" height="240" autoplay>
            <source src="<%= '/videos/'+category_id+'/'+video%>" type="video/mp4">
         </video>
       </div>
  <%})%>
  </div>


</body>
</html>

Integrate the fs module

To read content from the video folder, we will be utilizing the fs module.

Create category-specific folders inside your 'videos' directory and place your videos there.

Example: videos/1/myvideo.mp4

Add the following code snippet to your app.js file:

var fs = require('fs');
var ejs=require('ejs');

 // Set the view engine to ejs
 app.set('view engine', 'ejs');


app.get('/category/:id',function(req,res){

    fs.readdir(`./videos/${req.params.id}`, (err, files) => {
       console.log(files);
       res.render('pages/index',{videos:files,cateogry_id:req.params.id});
    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for automatically generating a new database in mongoose upon each new subscription to an application

I'm currently in the process of developing an application to help organizations keep track of their inventory and profit margins. To build the back-end, I've chosen to use NodeJS/Express/Mongoose. However, I am facing challenges when it comes to ...

Express Route Handler doesn't work for specific file types

I am currently working on setting up a route handler for requests to '.js' files. I have successfully configured middleware to serve static files from a "/dist" directory, which is functioning correctly. However, I am facing an issue where the r ...

Leveraging jQuery with Script Tags

Why is the script tag not executing when the dom is loaded? Consider this code snippet: History.Adapter.bind(window, 'statechange', function(e) { // Note: We are using statechange instead of popstate var State = History.getState(); ...

Design an HTML form that includes checkboxes for selecting multiple values

I am encountering an issue with a Checkbox field in an HTML input form. The values for the checkboxes are being fetched from another table and I am trying to select multiple users using these checkboxes. However, it seems like my code is not working as int ...

The error message "TypeError: [function] is not a function in Passport local strategy" indicates that

Currently, I am attempting to authenticate users locally using Passport.js without storing sessions and utilizing my own JWTokens. As I was following the steps outlined in this tutorial: Learn using JWT with Passport authentication While also referring ...

Adding substantial sections of HTML without any adjustments

While I am working on DOM manipulation, I have encountered the need to insert large blocks of HTML. I am looking for a more efficient way to do this rather than relying on concatenation or creating a messy code structure. Consider the simple code snippet b ...

Obtain a null value for the hidden field in ASP from a JavaScript parameter

Trying to transfer the selected parameter value from a dropdown menu to a hidden field but the hidden field always ends up empty. No errors in the JavaScript code when traced using browser debugger. What could be the issue? JavaScript $(document).ready( ...

Changing the appearance of a specific child component in React by referencing its id

There is an interface in my code. export interface DefaultFormList { defaultFormItems?: DefaultFormItems[]; } and export interface DefaultFormItems { id: string; name: string; formXml: string, isDefaultFormEnable: boolean; } I am looking ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

jQuery still not running despite using .ready

I have been attempting to run some jQuery code on my HTML page. After doing some research, I learned that using .ready may be necessary to ensure the DOM is fully loaded before executing the script. Despite this, I am still having trouble getting the scrip ...

Prevent jQuery toggle from animating content when toggling

When I use a simple jQuery .toggle function to show/hide my content on click, it slides in from left to right before reaching its final position. Is there a way to prevent this sliding effect? Is there a different jQuery method or property that I should be ...

Error: While implementing server side rendering with React-router 4, a TypeError occurred due to being unable to read the property 'pathname' of null

While developing a React app with webpack@2 and React-Router@4, everything works fine in development mode. However, when I try to switch to production mode with server-side rendering, I encounter the following error: TypeError: Cannot read property ' ...

Seeking advice on modifying the background color within the code? (Designer delving into the coding realm)

Seeking guidance on changing the background color within this code. (designer navigating the coding realm) <script src="https://cdn.rawgit.com/mrdoob/three.js/fdefb19b/examples/js/renderers/CanvasRenderer.js"></script> <script src="https ...

Nested UI routing with hidden display

I am working on a website using AngularJS and Ui-router. Index.html <body> <a href="#">Home Page</a> <div ui-view></div> </body> Javascript: .config(function($stateProvider, $urlRouterProvider) { $statePro ...

What could be the reason for the Checkbox's value not showing up after making changes?

In my React and Material UI project, I am facing an issue where I want to check all checkboxes in a list by simply checking one checkbox in a parent component. Despite passing down the correct value of the parent checkbox through props, the visual changes ...

What is the method for creating a MongoDB collection index that enforces uniqueness in a case-insensitive manner?

When designing a user schema, I require usernames to be case insensitive, ensuring no two usernames are similar even when taking into account capital letters. To achieve this, I initially added collation with a locale of 'en' and a strength of 2 ...

Executing an npm task from a JavaScript file in a parent/child process scenario

As someone who is still learning about child-process, I need some additional clarification on the topic. The Situation I am trying to find a way to execute one js file as a separate process from another js file. I want to pass a specific argument (a numb ...

Shifting Objects within Bootstrap 5 Navigation Menu

Hey there! I'm having some trouble aligning the items in a Bootstrap 5 navigation bar to the side, just like in this screenshot: https://i.sstatic.net/nxh80.png I tried adjusting the alignment but nothing changed on the site (I was using Live Server ...

The Content Security Policy is blocking other sources because it is set to 'self

Having these two inline script tags: <script async defer src="https://apis.google.com/js/api.js"></script> <script async defer src="https://accounts.google.com/gsi/client"></script> important to note: attempted ...

What is the best way to change the state of an Object?

I need to dynamically adjust the internalstatus based on the values of externalValues. If valueOne is true, then I want statusOne to be true. Similarly, if valueTwo is true, I want statusTwo to be true and statusOne to be false. const externalValues = { v ...