var http = require("http"); var fs = require("fs"); var server = http.createServer(function(req, res){}).listen(50082); var url = "http://s0.hao123img.com/res/img/logo/logonew.png"; //随机获取名称 function getName(){ var timer = new Date(); var arr = JSON.stringify(timer).replace(/:|-|"/g ,'').split('.'); var str = arr.join(''); console.log(str); return str; } load(url); function load(url){ http.get(url, function(res){ var imgData = ""; res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开 res.on("data", function(chunk){ imgData+=chunk; }); res.on("end", function(){ if(imgData){ console.log('下载成功!'); var path = "./image/"+getName()+".png"; console.log(path); fs.writeFile(path, imgData, "binary", function(err){ if(err){ console.log("down fail"); } console.log("down success"); }); }else{ console.log('下载失败!,图片路径不存在!'); } }); }); }