let http = require("http");
let fs = require("fs");
let path = require("path");
let cheerio = require("cheerio");
let iconv = require("iconv-lite");
let EventEmitter = require("events");
let targetUrl = "http://www.27270.com/ent/meinvtupian/"
//定义一个类继承由events导出的EventEmitter
class myEmitter extends EventEmitter{
init(){
//注册downHtmlSuccess,当触发这个事件时,调用里面的方法this.parseHtml(result)
this.on("downHtmlSuccess",(result)=>{
this.parseHtml(result)
})
//parseHtmlSuccess,当触发这个事件时,调用里面的方法this.downImages(result)
this.on("parseHtmlSuccess",(result)=>{
this.downImages(result)
})
//最开始运行的是下面这个方法
this.downHtml(targetUrl)
}
downHtml(targetUrl) {
let chunks = []
http.get(targetUrl,(response)=>{
response.on("data",(chunk)=>{
chunks.push(chunk)
})
response.on("end",()=>{
//重新编码原html的源代码,下面是死操作
let htmlTar = iconv.decode(Buffer.concat(chunks),"gb2312");
this.emit("downHtmlSuccess",htmlTar)
})
})
}
parseHtml(htmlTar){
let $ = cheerio.load(htmlTar);
let result = []
let imgTags = $("div.MeinvTuPianBox>ul>li>a>i>img").toArray();
for (let i = 0; i < imgTags.length; i++) {
/*★★★尤其要注意,这里要把每个元素转成DOM对象再取attr值,所以下面两行是错的*/
/*let src = imgTags[i].src
let imgName = imgTags[i].alt*/
let src = $(imgTags[i]).attr("src")
let imgName = $(imgTags[i]).attr("alt")
result.push({
src,
imgName
})
}
this.emit("parseHtmlSuccess",result)
}
downImages(result){
let targetDir = "images"
for (let i = 0; i < result.length; i++) {
let src = result[i].src
let imgName = result[i].imgName
http.get(src,(response)=>{
let filePath = path.join(targetDir,imgName+path.extname(src));
let writeStream = fs.createWriteStream(filePath);
response.pipe(writeStream)
})
}
}
}
//创建一个类并调用其init()方法
let emitter = new myEmitter();
emitter.init()