Use node’s request module to download pictures in batch.

  node.js, question

I want to download some pictures, which are stored on the website in this way.

http://a.com/1.jpg
 http://a.com/2.jpg
 http://a.com/3.jpg

My code is as follows:

var request = require('request');
var fs = require('fs');
var mkdir = require('mkdirp');

var preUrl = 'http://a.com/';
var dir = './images';

mkdir(dir, function(err) {
if(err) {
    console.log(err);
}
});
for(var i = 1; i <= 10; i加加){
  var trueUrl = preUrl 加 i 加 '.jpg';
  var name = i 加 '.jpg';
   request(trueUrl, function(err, response, body) {
  if(!err && response.statusCode == 200) {
      download(trueUrl, dir, name);
      console.log("Done" 加 trueUrl);
                }
      });                
}
var download = function(url, dir, filename) {
request.head(url, function(err, res, body) {
    request(url).pipe(fs.createWriteStream(dir 加 '/' 加 filename));
});
};

However, I found that the following part will not run at all, that is, if I enter console.log(111) on the following code, I will loop out 111 many times, while there is no movement on the following part. . .

request(trueUrl, function(err, response, body) {
      if(!err && response.statusCode == 200) {
          download(trueUrl, dir, name);
          console.log("Done" 加 trueUrl);
                    }
          });

What’s wrong with me? Can you give me some advice?


After waiting, it is basically the code above. He will always show donehttp://a.com/10.jpgBut it was not downloaded. . And computers will have special cards

In the end, it was only downloaded to 10.jpg.

The name variable in the asynchronous callback in the for loop is the same value.