node.js从url下载图片

我的问题是下载图像与未知的扩展(它可能是JPG,或PNG,或JPEG或BMP)从url。 所以我想检查图像的Content-Length,如果它大于0,则将其下载到文件,否则尝试使用另一个扩展名下载图像等。

var fs = require('fs'); var request = require('request'); var xml2js = require('xml2js'); var Q = require('q'); var baseUrl = 'http://test.com/uploads/catalog_item_image_main/'; Q.nfcall(fs.readFile, "./test.xml", "utf8") .then(parseSrting) .then(parseProductsAsync) .then(processProductsAsync) ; function parseSrting(data){ return Q.nfcall(xml2js.parseString,data); } function parseProductsAsync(xmljsonresult){ return xmljsonresult.product_list.product; } function processProductsAsync(products){ products.map(function(product){ var filename = product.sku + ""; // - where is image name filename = filename.replace(/\//g, '_'); console.log('Processing file ' + filename); var imageUrl = baseUrl + filename + '_big.'; // + image extension //There I want to check Content-Length of the image and if it bigger then 0, download it to file, //else try download image with another extension and etc. }); } 

我为Node.js使用Q promise模块来避免callback地狱,但有人可以帮我检查图像大小,并将其保存到文件?

您可以检查响应的状态码。 如果是200,那么图像就没有问题了。

您可以使用一组文件扩展名和一个recursion方法按顺序尝试每个文件扩展名。 使用request模块,你可以这样做:

 function processProductsAsync(products){ products.map(function(product){ var filename = product.sku + ""; // - where is image name filename = filename.replace(/\//g, '_'); console.log('Processing file ' + filename); var imageUrl = baseUrl + filename + '_big.'; // + image extension fetchImage(imageUrl, filename, 0); }); function fetchImage(url, localPath, index) { var extensions = ['jpg', 'png', 'jpeg', 'bmp']; if (index === extensions.length) { console.log('Fetching ' + url + ' failed.'); return; } var fullUrl = url + extensions[index]; request.get(fullUrl, function(response) { if (response.statusCode === 200) { fs.write(localPath, response.body, function() { console.log('Successfully downloaded file ' + url); }); } else { fetchImage(url, localPath, index + 1); } }); }