如何从节点服务器下载文件(仅使用节点模块,不使用快速等)

How to download a file from node server(using only node modules, no express, etc)

本文关键字:节点 模块 服务器 下载 文件      更新时间:2023-09-26

>我目前正在为下载功能编写处理程序。当用户从他''her浏览器单击下载按钮时,将调用下载处理程序,然后启动下载(仅限mp3文件(。我在 php 上工作,但此后我将项目中的所有内容都更改为 Node,我似乎无法让最后一部分在 Node 上工作。

这是我之前使用的 php 代码:

<?php 
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=".($_GET['title']));
  readfile($_GET['path']);
?>

这是 Node 的新代码:

function download(response, request){
 var body = [];
   request.on('data', function(chunk) {
   body.push(chunk);
 });
 request.on('end', function() {
    
   body = Buffer.concat(body).toString();
   var data = qs.parse(body);
   var title = data.songTitle;
   var filePath =  __dirname + "/../myproject/songs/"+title+".mp3";
  
   fs.open(filePath,'r',function(err, fd){
      
      if(!err){
          
          fs.readFile(fd, function(err, data){
             
             if(!err){
                
                var rs = fs.createReadStream(filePath);
                response.writeHead(200, {"Content-Type": "application/octet-stream", 
                                         "Content-Disposition": "attachment; filename="+title+".mp3",
                                         "Content-Length" : data.length});
                rs.pipe(response);
                response.on("end",function(){
                    fs.close(fd);
                });  
                
             }else{
                 
                 console.log("Error while trying to read: ", err); 
                 
             }
             
          });
          
      }else{
          console.log("Error could not open: ", err);
      }
      
  });
  
});

尝试下载时,我没有收到任何错误,但没有任何反应。我也尝试过"audio/mpeg3"作为内容类型,什么都没有。对正在发生的事情有什么想法吗?我正在尝试在不使用第三方模块的情况下执行此操作。请注意,函数下载不会作为 http.createServer(( 的回调函数传递。因此,响应和请求的顺序不是问题:)

看起来你切换了requestresponse.此外,您可以使用 fs.stat() 来确定文件大小,而不是使用 fs.open()/fs.readFile() 来确定文件大小,这应该对资源更加友好(因为它不需要先将整个文件加载到内存中(:

function download(request, response) {
  var body = [];
  request.on('data', function(chunk) {
    body.push(chunk);
  });
  request.on('end', function() {
    var data     = qs.parse(Buffer.concat(body).toString());
    var title    = data.songTitle;
    var filePath = title + '.mp3';
    fs.stat(filePath, function(err, stats) {
      if (err) {
        response.statusCode = 500;
        return response.end();
      }
      response.writeHead(200, {
        "Content-Type"        : "application/octet-stream",
        "Content-Disposition" : "attachment; filename="+title+".mp3",
        "Content-Length"      : stats.size,
      });
      fs.createReadStream(filePath).pipe(response);
    });
  });
}