【问题标题】:Download a youtube video file in node js using ytdl使用 ytdl 在节点 js 中下载 youtube 视频文件
【发布时间】:2017-06-17 13:52:21
【问题描述】:

我想让用户能够使用 node-ytdl 下载 youtube 视频。 例如,当客户端对某个路由发出 GET 请求时,应下载视频作为响应。

  var ytdl = require('ytdl-core');
  var express= require('express');

   //Init App Instance
    var app=express();



 app.get('/video',function(req,res){


 var ytstream=ytdl("https://www.youtube.com/watch?v=hgvuvdyzYFc");


ytstream.on('data',function(data){
   res.write(data);
})

ytstream.on('end',function(data){
    res.send();
})

})

以上是我的 nodejs 代码。即使在网络中它似乎下载响应它不会让用户下载为文件。我不想在服务器上存储任何文件。如果有人可以帮助我如何解决这个问题,那就太好了。

【问题讨论】:

标签: node.js video youtube request


【解决方案1】:

好的,所以创建一个数组,然后在 data 事件中向其中添加数据。在end 上,发送数组。这是一个例子:

const ytdl = require("ytdl-core"),
      app = require("express")();

app.get("/video", (req, res) => {
  let arr = [], vid = ytdl("https://www.youtube.com/watch?v=hgvuvdyzYFc");
  vid.on("data", d => arr.push(d));
  vid.on("end", () => res.send(arr));
});

【讨论】:

    【解决方案2】:

    res 对象是一个可写流,因此您可以像这样直接将 ytdl 的输出通过管道传输到 res 对象 -

        ytdl("http://www.youtube.com/watch?v=xzjxhskd")
          .on("response", response => {
            // If you want to set size of file in header
            res.setHeader("content-length", response.headers["content-length"]);
          })
          .pipe(res);
    

    【讨论】:

      【解决方案3】:

      您还必须传递标题。试试看:

      app.get('/video', (req, res) => {
          var url = "https://www.youtube.com/watch?v=hgvuvdyzYFc";
          res.header("Content-Disposition", 'attachment; filename="Video.mp4');
          ytdl(url, {format: 'mp4'}).pipe(res);
      });
      

      如果有人仍然收到错误,只需通过运行将包更新到最新版本:

      npm i ytdl-core@latest
      

      【讨论】:

        猜你喜欢
        • 2022-06-17
        • 2017-04-26
        • 2020-05-05
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 2012-12-31
        相关资源
        最近更新 更多