JSDOM 自动下载其他网站的图片
var jsdom = require(“jsdom”); var http = require(“http”); var fs = require(“fs”);
function catchCore(){ jsdom.env( “http://www.qiushibaike.com/hot/”, [“http://code.jquery.com/jquery.js”], function (errors, window) { if(errors){ console.log(errors); } var $ = window.$; // console.log($(“body”).html()); console.log($(“img”).length);
$("img").each(function(idx,obj){
var src = obj.src;
if(/pic.qiushibaike.com/.test(src)){
http.get(src, function(res) {
res.setEncoding('binary');//二进制(binary)
var imageData ='';
res.on('data',function(data){//图片加载到内存变量
imageData += data;
}).on('end',function(){//加载完毕保存图片
var imageName = src.substr(src.length-8,8);
fs.writeFile('public/images/'+imageName, imageData, 'binary', function (err) {//以二进制格式保存
if (err) throw err;
console.log('file saved');
});
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
});
}
);
}
exports.start = catchCore;