1

I want to let users download a video from my AWS S3 bucket. The video format is MP4:

app.get("/download_video", function(req,res) {
    filename = "s3.xxx.amazon.com/bucketname/folder/video_example.mp4";
    // im stuck on what i can do here
});

There are a lot of examples on how to download images and textfiles online using nodejs, but I can't find anything on videos.

antinescience
  • 2,339
  • 23
  • 31
unknown
  • 846
  • 3
  • 15
  • 38

3 Answers3

7
use strict

const Fs = require('fs')
const Path = require('path')
const Listr = require('listr')
const Axios = require('axios')

function one (tasks) {

  tasks.run()
   .then(process.exit)
   .catch(process.exit)
}


if (process.argv) {

  const tasks = [{
    title: 'Downloading',
    task: async (ctx, task) => {
      const url = 'https://s3.xxx.amazon.com/bucketname/folder/video_example.mp4"'
      const path = Path.resolve(__dirname, 'media', 'video.mp4')

      const response = await Axios({
        method: 'GET',
        url: url,
        responseType: 'stream'
      })

      response.data.pipe(Fs.createWriteStream(path))

      return new Promise((resolve, reject) => {
        response.data.on('end', () => {
          resolve()
        })

        response.data.on('error', err => {
          reject(err)
        })
      })
    }
  }]

  one(new Listr(tasks))
}
Muhammad Noman
  • 1,344
  • 1
  • 14
  • 28
Rama
  • 185
  • 2
  • 4
2

Try this

const fetch = require('node-fetch');
const fs = require('fs');
 
const response = await fetch(yourUrl);
const buffer = await response.buffer();

 fs.writeFile(`./videos/name.mp4`, buffer, () => 
   console.log('finished downloading video!'));                                          
Mihran
  • 41
  • 8
1

Third-party modules are no longer needed as of Node.js v18.

import { createWriteStream } from 'node:fs';
import { Readable } from 'node:stream';

const videoFileUrl = 'https://sveltejs.github.io/assets/caminandes-llamigos.mp4';
const videoFileName = 'video.mp4';

if (typeof (fetch) === 'undefined') throw new Error('Fetch API is not supported.');

const response = await fetch(videoFileUrl);

if (!response.ok) throw new Error('Response is not ok.');

const writeStream = createWriteStream(videoFileName);

// Reference https://stackoverflow.com/a/66629140/12817553
const readable = Readable.fromWeb(response.body);

readable.pipe(writeStream);

await new Promise((resolve, reject) => {
    readable.on('end', resolve);
    readable.on('error', reject);
});
Hyunbin
  • 423
  • 4
  • 6
  • Can you provide additional wrapping to this; assuming success, where is the output? How do you access the downloaded file? e.g. a case where a large image or video is downloaded. – Kalnode Jun 22 '23 at 14:13
  • 1
    @Kalnode Assuming that the final promise has resolved, the file is saved as video.mp4 in the current directory where the script is being executed. – Hyunbin Jun 23 '23 at 01:24