最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how can i download a video mp4 file using node.js? - Stack Overflow

programmeradmin2浏览0评论

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/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.

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./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.

Share Improve this question edited Mar 30, 2013 at 0:24 antinescience 2,35923 silver badges31 bronze badges asked Mar 30, 2013 at 0:19 unknownunknown 8663 gold badges16 silver badges38 bronze badges 2
  • I know absolutely nothing about nodejs (well, a little, I guess), but shouldn't downloading a video file be just the same as downloading an image? – antinescience Commented Mar 30, 2013 at 0:21
  • aws.amazon./sdkfornodejs – Shanimal Commented Mar 30, 2013 at 0:23
Add a ment  | 

4 Answers 4

Reset to default 8
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./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))
}

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!'));                                          

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./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);
});
const axios = require('axios');
const fs = require('fs'); 
const path = require('path');
const { send } = require('process');
const express = require('express');
const app = express();

 const videoUrl = 'https://mondatastorage.googleapis./gtv-videos-bucket/sample/BigBuckBunny.mp4'; // Replace with the actual video URL
 const outputFilePath = path.join(__dirname, 'downloaded-video.mp4');

  async function downloadVideo() {
try {
    const response = await axios.get(videoUrl, { responseType: 'stream' });
    const totalSize = response.headers['content-length'];
    let downloadedSize = 0;
    const writer = fs.createWriteStream(outputFilePath);


    response.data.on('data', (chunk) => {
        downloadedSize += chunk.length;
        const percent = (downloadedSize / totalSize) * 100;
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        process.stdout.write(`Downloading... ${percent.toFixed(2)}%`);
    });


    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject);
    });
} catch (error) {
    console.error('Error downloading video:', error);
}
}

 // Function to read a video file and return its byte data
 function convertVideoToBytes(filePath) {
return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
        if (err) {
            reject(err);
        } else {
            resolve(data);
        }
    });
    });
     } 

     app.get('/videoDownload', (req, res) => {



    downloadVideo()
    .then(() => {
        console.log('Video downloaded successfully to', outputFilePath);
    })
    .catch((error) => {
        console.error('Error:', error);
    });

    })

  app.listen(3000);
    
发布评论

评论列表(0)

  1. 暂无评论