我的问题是从url下载未知扩展名的图片(可能是jpg,png,jpeg或bmp)。因此我想检查图片的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 promises模块来避免回调地狱,但有人可以帮助我检查图片大小并将其保存到文件中吗?
request
函数可以吗?请使用普通的回调函数,而不是 Promise,告诉我们您需要什么,这样我们就可以帮助您避免回调地狱。 - Bergi