You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
25 Min
36 Seg
Curso de Fundamentos de Node.js

Curso de Fundamentos de Node.js

Oscar Barajas Tavares

Oscar Barajas Tavares

Servidor nativo y streaming de video en Node.js

20/20
Resources

Creating Node.js servers that handle multimedia resources such as videos is a fundamental skill for modern web developers. Understanding how Node.js native streams, buffers and modules work allows you to build efficient applications that optimize memory usage and improve user experience. In this content, we will explore how to create a server that streams video in chunks, applying essential Node.js concepts.

How to create a video streaming server with Node.js?

When we need to stream large files such as videos over the web, it is not efficient to load the entire file into memory before sending it to the client. Instead, we can use streams to read and send the file in small chunks, which optimizes the use of server resources and allows the client to start playing the video before it is fully downloaded.

To create our video streaming server, we need to use several native Node.js modules:

  • http: To create the web server.
  • fs: To work with the file system
  • path: To handle the file paths

Let's start by creating a new file called server-video.js and importing the necessary modules:

const http = require('http');const fs = require('fs');const path = require('path');

How to configure the server to stream videos?

Once the modules are imported, we can create our HTTP server that will respond to video requests:

const server = http.createServer((req, res) => { if (req.url === '/video') { // Video file path const videoPath = path.join(__dirname, 'video.mp4');    
 // Get file information const stat = fs.statSync(videoPath);    
 // Set response headers res.writeHead(200, { 'Content-Type': 'video/mp4', 'Content-Length': stat.size });    
 // Create a read stream const readStream = fs.createReadStream(videoPath);    
 // Counter to monitor chunks let chunkCounter = 0;    
 // Event for each data chunk readStream.on('data', (chunk) => {  chunkCounter++; console.log(`Chunk ${chunkCounter}: ${chunk.length} bytes read and sent`); }); });    
 // Connect the read stream to the response readStream.pipe(res); } else { // Response for routes not found res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); } } });
server.listen(3005, () => { console.log('Server is running on http://localhost:3005');});

This code creates a server that listens on port 3005 and responds to requests to the /video path by transmitting an MP4 file. For any other path, it returns a 404 error.

How do streams and buffers work in this process?

Streams are one of the most powerful features of Node.js. On our server, we use fs.createReadStream() to read the video file in small chunks instead of loading it completely into memory. This is especially useful for large files like videos.

Buffers are the blocks of data that are transmitted across streams. Each time the stream reads a portion of the file, it generates a 'data' event with a buffer containing that portion of data. In our code, we capture these events to count and log each chunk that is sent.

The readStream.pipe(res) line connects the read stream with the HTTP response, which means that each fragment read from the file is automatically sent to the client.

How to test and visualize the server performance?

To test our server, we need to:

  1. Get a test video file: you can download a sample MP4 video and place it in the root of your project with the name "video.mp4".

  2. Start the server: Run the file with Node.js:

    node server-video.js

    Or if you prefer to have the server restart automatically when you make changes:

    node --watch server-video.js
  3. Access the video: Open your browser and visit http://localhost:3005/video

How to watch the streaming process in action?

To better visualize how the video snippets are streamed, you can:

  1. Open the browser's developer tools (F12).
  2. Go to the "Network" tab
  3. Simulate a slow connection (select "3G" in the network speed selector)
  4. Load the page http://localhost:3005/video

This will slow down the video download, allowing you to watch on the server console as the fragments are sent one by one. You will see messages like:

Chunk 1: 16384 bytes read and sentChunk 2: 16384 bytes read and sentChunk 3: 16384 bytes read and sent...

This process demonstrates how Node.js efficiently handles large files without consuming too much memory, since it only needs to keep one chunk of the file in memory at a time.

What are the practical applications of this technique?

This streaming technique is not just limited to videos. It is widely used in real-world applications for:

  • Video streaming platforms such as YouTube or Netflix.
  • Audio services such as Spotify or podcasts
  • Downloading large files
  • Real-time data transmission
  • APIs that handle large volumes of data

Node.js' ability to handle I/O operations asynchronously and efficiently makes it ideal for these types of applications where resource optimization is crucial.

Streaming data is a fundamental concept in modern web development, and mastering these techniques will allow you to create more efficient and scalable applications. Have you ever implemented a streaming server? Share your experience in the comments and continue exploring the fascinating world of Node.js.

Contributions 3

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Insisto, tuvimos una clase de console.count ```js readStream.on('data', (chunk) => { console.count('chunks'); console.log(`Chunk size: ${chunk.byteLength} bytes`); }); ```Y ya no hay necesidad de hacer un let counterChunks
Dos comentarios: 1-Hay un problema con el examen?, cuando quiero ingresar me devuelve al home de Platzi. 2- Creo que falt贸 aclarar que como este curso es introductorio casi todas las funciones que usamos (sobre todo en fs) son sincronicas pero que no es la forma que se usa en un servidor de producci贸n.
No se puede tomar el examen te redirige al pagina de inicio