DEV Community

Sávio Santos
Sávio Santos

Posted on

 

Streaming Video with Nestjs

What do you need to be done?

  • Create a route that will serve the video you want to upload:
@Get('/video-example')
  getFile(@Res({ passthrough: true }) res): StreamableFile {
    const file = createReadStream(join(process.cwd(), 'videos/video.mp4'));
    res.set({
      'Content-Type': 'video/mp4',
      'Content-Disposition': 'attachment; filename="video.mp4"',
    });
    return new StreamableFile(file);
}
Enter fullscreen mode Exit fullscreen mode
  • Consume the video using the video tag on your webpage:
<video width="80%" height="50%" controls>
   <source src="/video-example" type="video/mp4">
</video>
Enter fullscreen mode Exit fullscreen mode
  • Result (access localhost:3000):

Image description

See on Github: https://github.com/savi8sant8s/nestjs-video-streaming-example

Top comments (5)

Collapse
 
micalevisk profile image
Micael Levi L. C. • Edited

cool! another way would be:

@Get()
@Header('Content-type', 'video/mp4')
@Header('Content-Disposition', 'inline; filename="video.mp4"')
getFile(): StreamableFile {
  const file = createReadStream(join(process.cwd(), 'videos/video.mp4'));
  return new StreamableFile(file);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
savi8sant8s profile image
Sávio Santos

Even better. very cool!!

Collapse
 
xgeek116 profile image
rm116

@micalevisk How a frontend client like react will receive the StreamableFile(file) ? If it was a large PDF file for example ? is there a way to send it / receive it piece by piece ?

Collapse
 
xgeek116 profile image
rm116

@savi8sant8s How a frontend client like react will receive the StreamableFile(file) ? If it was a large PDF file for example ? is there a way to send it / receive it piece by piece ?

Collapse
 
savi8sant8s profile image
Sávio Santos • Edited

you can try this article: medium.com/@storrisi/how-to-show-a...

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.