【问题标题】:pipe works on localhost but not on remote nodejs管道适用于本地主机但不适用于远程nodejs
【发布时间】:2017-05-01 14:25:43
【问题描述】:

我正在尝试使用 ytdl-core 模块将 youtube 音频下载到我的本地磁盘(我计算机上的某个路径)。

我创建了一个 API,我可以使用请求的 youtube url 和我希望保存文件的目标文件夹来调用它。

app.get('/api/downloadYoutubeVideo', function (req, res) {  
var videoUrl = req.query.videoUrl;  
var destDir = req.query.destDir;    

ytdl.getInfo(videoUrl, function(err, info){
        var videoName = info.title.replace('|','').toString('ascii');       

        var stream = ytdl(videoUrl, { filter: 'audioonly'})
                       .pipe(fs.createWriteStream(destDir + '\\' + videoName + '.mp3'));

        stream.on('finish', function() {
            res.writeHead(204);
            res.end();
        });             
    });         
}); 

问题是当我在本地主机上调用 api 时(例如:localhost:11245/api/downloadYoutubeVideo?videoUrl=https://www.youtube.com/watch?v=E5kJDWQSBUk&destDir=C:\test) 它工作正常,文件确实下载到“C:\test”。

但是当我调用遥控器上的 api 时(例如:http://sometest.cloudno.de/api/downloadYoutubeVideo?videoUrl=https://www.youtube.com/watch?v=02BAlrAkuCE&destDir=C:\test)

它不会在目录中创建文件...

我已经搜索了答案,但没有找到...

【问题讨论】:

    标签: javascript node.js youtube stream pipe


    【解决方案1】:

    您的遥控器上是否已经存在C:\test?如果不是,在创建目录之前您不能使用fs.createWriteStream(),它不会为您隐式创建目录。由于您没有在监听 'error' 事件,因此您甚至不会知道这是问题所在,因为您没有捕获它。

    下面的代码示例将检查destDir 是否存在,如果不存在将在继续之前创建它。

    const fs = require('fs');
    const sep = require('path').sep;
    
    function checkAndMakeDir(dir, cb) {
      fs.access(dir, (err) => {
        if (err)
          fs.mkdir(dir, (err) => {
            if (err)
              return cb(err);
    
            return cb();
          });
        else
          return cb();
      });
    }
    
    app.get('/api/downloadYoutubeVideo', function (req, res) {
      let videoUrl = req.query.videoUrl;
      let destDir = req.query.destDir;
    
      checkAndMakeDir(destDir, (err) => {
        if (err) {
          res.writeHead(500);
          return res.end();
        }
    
        ytdl.getInfo(videoUrl, function (err, info) {
          let videoName = info.title.replace('|', '').toString('ascii');
          let saveStream = fs.createWriteStream(`${destDir}${sep}${videoName}.mp3`);
    
          saveStream.once('error', (err) => {
            console.log(err);
            res.writeHead(500);
    
            return res.end();
          });
    
          saveStream.once('finish', () => {
            res.writeHead(204);
            return res.end();
          });
    
          ytdl(videoUrl, {filter: 'audioonly'})
            .once('error', (err) => {
              console.log('Read Stream Error', err);
    
              res.writeHead(500);
              return res.end();
            })
            .pipe(saveStream);
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 2012-09-23
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多