【问题标题】:Node.js download multiple filesNode.js 下载多个文件
【发布时间】:2013-06-29 12:20:55
【问题描述】:

我需要从 url 下载多个文件。我在文件中有它们的列表。我该怎么做?我已经做到了,但它不起作用。在开始下一个 wan 之前,我需要等到最后一次下载完成。我该怎么做?

【问题讨论】:

  • 您需要从 url 给出的页面中提取文件吗?或者你只是想下载网址?

标签: node.js file download


【解决方案1】:

您想在此之前从文件的回调中调用下载函数。我拼凑了一些东西,请不要认为它漂亮或生产就绪;-)

var http = require('http-get');

var files = { 'url' : 'local-location', 'repeat-this' : 'as often as you want' };

var MultiLoader = function (files, finalcb) {

        var load_next_file = function (files) {

                if (Object.keys(files) == 0) {
                        finalcb(null);
                        return;
                }   

                var nexturl = Object.keys(files)[0];
                var nextfnname = files[nexturl];

                console.log('will load ' + nexturl);
                http.get(nexturl, nextfnname, function (err, result) {
                        console.log('loaded ' + nexturl);
                        delete files[nexturl];
                        load_next_file(files);
                }); 
        };  

        load_next_file(JSON.parse(JSON.stringify(files)));

};

MultiLoader(files, function () { console.log('finalcb'); }); 

http-get不是标准的node模块,可以通过npm install http-get安装。

【讨论】:

  • 最大的问题是,如何读取文件在哪里是要下载的文件列表。请问我该怎么做?
【解决方案2】:

我想这就是你要找的。​​p>

const fs = require('fs')
const https = require('https')

const downloadFolderPath = 'downloads'
const urls = [
  'url 1',
  'url 2'
]

const downloadFile = url => {
  return new Promise((resolve, reject) => {
    const splitUrl = url.split('/')
    const filename = splitUrl[splitUrl.length - 1]
    const outputPath = `${downloadFolderPath}/${filename}`
    const file = fs.createWriteStream(outputPath)

    https.get(url, res => {
      if (res.statusCode === 200) {
        res.pipe(file).on('close', resolve)
      } else {
        reject(res.statusCode)
      }
    })
  })
}

if (!fs.existsSync(downloadFolderPath)) {
  fs.mkdirSync(downloadFolderPath)
}

let downloadedFiles = 0
urls.forEach(async url => {
  await downloadFile(url)
  downloadedFiles++
  console.log(`${downloadedFiles}/${urls.length} downloaded`)
})

【讨论】:

    【解决方案3】:

    你可以在 node js 中使用 fs (var fs = require('fs');) 读取文件

    fs.readFile('<filepath>', "utf8", function (err, data) {
            if (err) throw err;
            console.log(data);
                    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多