【问题标题】:How to download file from server using nodejs如何使用nodejs从服务器下载文件
【发布时间】:2020-04-16 05:47:32
【问题描述】:

我想使用 expressjs 将文件从其他网站下载到我的电脑

我尝试使用:res.download 进行下载,但它似乎只能在我自己的服务器上运行

这是我的代码:

res.download('http://apkleecher.com/download/dl.php?dl=com.instagram.android', 'folder', function(err){
                if (err) {
                    console.log(err);
                } else {

                }
            });

它返回错误:

{ 错误:ENOENT:没有这样的文件或目录,stat '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android' 错误号:-2, 代码:'ENOENT', 系统调用:'stat', 路径:'/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android', 暴露:假, 状态码:404, 状态:404 }

在我的猜测中,问题出在 url 的路径上。

【问题讨论】:

标签: express download


【解决方案1】:

将我的评论变成答案,因为它对您有用...

您可以使用http.get()request() module in 节点从远程Web 服务器获取资源。如果您喜欢在异步操作中使用 Promise,那么 request-promise module 是 request 模块的 Promisified 版本,效果很好。

您也可以只使用普通的http.get(),但工作量要大得多,因为您必须阅读流,而不是自己阅读结果并安装适当的错误处理,request() 模块为您提供了所有这些功能简单的调用。

这是一个使用 request-promise 模块的简单示例:

const rp = require('request-promise');
rp('http://www.google.com').then(function (htmlString) {
    // Process html...
}).catch(function (err) {
    // process error here
});

【讨论】:

    【解决方案2】:

    res.download 需要本地文件系统的路径。

    试试这个:

    res.redirect("http://apkleecher.com/download/dl.php?dl=com.instagram.android")

    【讨论】:

      【解决方案3】:

      下载远程文件的最佳方法是使用流。它使用少量内存

      **npm i got**
      //========================
      const got=require('got');
      const fs=require('fs');
      const path=require('path');
      
      file_downloader(link,file_name){
      var file_path = path.join(__dirname,file_name);
        await got.stream(encodeURI(link))
              .on('response', async (data) => {
                //first response check headers like ['content-length']
              })
              .on('error', async (error) => {
      
                      console.log("===========Stream Error======= ");
                      console.log(error);
                      console.log("===========//End Stream Error======= ");
      
              })
              .on('downloadProgress', async (progress) => {
      
                   console.log(file.name, progress);
      
              })
              .pipe(fs.createWriteStream(file_path));
      }
      

      【讨论】:

        猜你喜欢
        • 2015-10-18
        • 2013-12-14
        • 2017-07-06
        • 1970-01-01
        • 2015-06-14
        • 2017-02-25
        • 2019-03-30
        相关资源
        最近更新 更多