听说最近下载妹子图很火?
Nodejs (javascrpt)自然不能落后~
虽然从没写过像样的Nodejs程序,但作为至少翻过书的前端同学来说,Nodejs用得还蛮顺手的哈~ 花了一点事件学习了下Nodejs的网页获取和文件下载方法,没事乱捣腾就写了这个半成品的下载器
使用方法:
1)新建一个download目录 2)新建download.js(其实名字随便取),并复制到download目录下 3)复制两段代码到download.js中 4)打开命令行工具,并将当前目录转到与download目录下 5)在命令行中输入:node download.js 6)等着收妹子图吧~
简单的妹子图对象(新增断定下载支持)
this.id = 1;
this.initialize.call(this,options);
return this;
}
Mzitu.prototype = {
constructor: Mzitu,initialize: function _initialize(options) {
this.baseUrl = options.baseUrl;
this.dir = options.dir || '';
this.reg = options.reg;
this.total = options.total;
this.page = options.from || 1;
},start: function _start() {
this.getPage();
},getPage: function _getPage() {
var self = this,data = null;
if (this.page <= this.total) {
http.get(this.baseUrl + this.page,function (res) {
res.setEncoding("utf8");
res.on('data',function (chunk) {
data += chunk;
}).on('end',function () {
self.parseData(data);
});
});
}
},parseData: function _parseData(data) {
var res = [],match;
while ((match = this.reg.exec(data)) != null) {
res.push(match[1]);
}
this.download(res);
},download: function _download(resource) {
var self = this,currentPage = self.page;
resource.forEach(function (src,idx) {
var filename = src.substring(src.lastIndexOf('/') + 1),writestream = fs.createWriteStream(self.dir + filename);
http.get(src,function (res) {
res.pipe(writestream);
});
writestream.on('finish',function () {
console.log('page: ' + currentPage + ' id: ' + self.id++ + ' download: ' + filename);
});
});
self.page++;
self.getPage();
}
};
妹子图下载启动方式
/g,total: 141,from: 1 });mzitu.start();