使用Node js从网上下载文件并循环

时间:2018-07-16 11:42:42

标签: javascript node.js

我想使用以下代码从网上下载多个文件:

Sub Files()
  Dim wb As Workbook
  ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\testfile.xlsm"
  Set wb = Workbooks.Open("C:\Users\" & Environ("Username") & "\Desktop\" & "testfile.xlsm", UpdateLinks:=False)
  Call Unprotection(wb)
  MsgBox ("File saved successfully on desktop.")
  ThisWorkbook.Close SaveChanges = False
End Sub

Sub Unprotection(wb As Workbook)
  Dim b As Worksheet
  For Each b In wb.Worksheets
    b.Unprotect Password:="abc"
  Next b
End Sub

我想要的结果是:下载了多个文件,文件名为 filename1-5.jar 。我得到的结果只是1个文件,文件名为 filename5.jar (或循环中i var的最后一个值)。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您的请求是异步的,它仅在循环完成后才执行,因此文件名中的5。一种解决方案是通过创建一个新函数并在循环内调用它来分别威胁代码:

var fs = require('fs');
var http = require('http');
var request = require('request');

var file;

function customRequest(i){

  //CHECK IF REMOTE FILE EXISTS
  return request('http://webaddress.com/filename' + i + '.jar', function(err, resp) {

    //IF EXISTS DO
    if (resp.statusCode == 200) {
      //DOWNLOAD DATA AND CREATE A NEW .JAR FILE
      file = fs.createWriteStream('D:\\filename' + i + '.jar');
      http.get('http://webaddress.com/filename' + i + '.jar', function(response) {
        response.pipe(file);
        file.on('finish', function() {
          file.close();
        });
      });
    }

    //FILE DOES NOT EXIST
  });

}

for (var i = 1; i <= 5; i++) {
   customRequest(i)
}

答案 1 :(得分:1)

就像@Ionut所说的,您的请求是异步的,因此您需要等待

let fs = require('fs');
let request = require('request');

let download = (uri, filename) => {
    return new Promise ((resolve, reject) => {
        request.head(uri, function(err, res) {

            if (res.statusCode === 200) {
                request(uri).pipe(fs.createWriteStream(filename)).on('close', resolve);
            } else {
                reject(res.statusCode);
            }
        });
    });
};

let promises = [];

for(let i = 1; i <= 5; i++) {
    promises.push(download('http://webaddress.com/filename' + i + '.jar', 'D:\\filename' + i + '.jar'));
}

Promise.all(promises).then(() => {
    process.exit(0);
});