nodejs试图让远程文件向用户打开

问题描述 投票:0回答:1

想知道我在这里做错了什么。我想要的只是我已连接以下载到用户的mp3。

我理想的解决方案是可以在其前面添加mp3。

const express = require('express');
var fs = require('fs');
request = require('request');
const http = require("http");
const https = require("https");

router.get('/a/:url(*)', (req, res) =>{
        res.set({
            "Content-Type": "audio/mp3",
           // 'Transfer-Encoding': 'chunk',
          //  'Content-Disposition': 'attachment'
        });

        const file = fs.createWriteStream("audio.mp3");
        var url = req.params.url.substr(0); 
        console.log(url);




https.get('https://storage.googleapis.com/ad-system/testfolder/OUTOFAREA.mp3', response => {
                response.pipe(file);

            });

https.get(url, response => {
                response.pipe(file);

            });
            file.push(res);
        });
        module.exports = router;

我遇到的错误是

TypeError: file.push is not a function
    at router.get (/root/adstichrplayer/server/routes/podcast.js:131:10)
    at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:95:5)
    at next (/root/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/root/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:95:5)
    at /root/node_modules/express/lib/router/index.js:281:22
    at param (/root/node_modules/express/lib/router/index.js:354:14)
    at param (/root/node_modules/express/lib/router/index.js:365:14)
    at param (/root/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/root/node_modules/express/lib/router/index.js:410:3)
    at next (/root/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/root/node_modules/express/lib/router/index.js:174:3)
    at router (/root/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/root/node_modules/express/lib/router/index.js:317:13)
    at /root/node_modules/express/lib/router/index.js:284:7
node.js fs
1个回答
0
投票

您正在尝试在.push上使用Writeable stream。只有实现Readable接口的流才能调用.push

如果您不需要将文件持久保存到磁盘,则无需创建WriteStream。您可以直接通过管道传递到Express的res对象:

  router.get('/a/:url(*)', (req, res) => {
  res.set({
    'Content-Type': 'audio/mp3',
    // 'Transfer-Encoding': 'chunk',
    //  'Content-Disposition': 'attachment'
  });

  const url = req.params.url.substr(0);
  console.log(url);

  https.get(url, response => {
    // pipe response from HTTP request to Express res object
    response.pipe(res);
  });
});


© www.soinside.com 2019 - 2024. All rights reserved.