Sitemap
Android & Node js

Android & Node js

Experienced Android Developer & skilled writer on Medium. Passionate about tech, with 5+ years in mobile app development. Shares insights & advice.

Playing video from server using node js

2 min readJul 10, 2023

play a video from a server using Node.js. We’ll use the Express framework to create a simple server and the HTML5 video tag to display the video in the browser.

First, make sure you have Node.js and Express installed. You can install them using npm (Node Package Manager) by running the following commands in your project directory:

npm init -y
npm install express

Next, create a new file called server.js and add the following code:

const express = require('express');
const app = express();

// Define a route for serving the video file
app.get('/video', (req, res) => {
const videoPath = 'path/to/your/video.mp4'; // Path to your video file
const stat = fs.statSync(videoPath);
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(videoPath, { 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(videoPath).pipe(res);
}
});

// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

In this example, we define a route /video that serves the video file. The route handles both full requests and range requests for partial content (e.g., seeking within the video).

Get Android & Node js’s stories in your inbox

Join Medium for free to get updates from this writer.

Make sure to replace 'path/to/your/video.mp4' with the actual path to your video file. Also, you may need to import the fs module at the beginning of the file:

const fs = require('fs');

Save the server.js file and run it using the following command:

node server.js

Now, if you navigate to http://localhost:3000/video in your browser, it should start playing the video.

This is a basic example, and you can extend it further to handle error cases, serve multiple videos, or add authentication if needed. But I hope this gives you a good starting point for playing videos from a server using Node.js.

Happy Coding!

--

--

Android & Node js
Android & Node js

Written by Android & Node js

Experienced Android Developer & skilled writer on Medium. Passionate about tech, with 5+ years in mobile app development. Shares insights & advice.