response返回都是html/text,向前台输出一张图片用的image/jpeg,服务器读取图片的时候是按照binary的二进制方式读取,给客户端返回的时候也按照binary二进制的方式返回。
从服务器读取一张图片给客户端输出:
效果:输入localhost:8003直接显示图片
readImg.js
var http=require('http');
var imgFile=require('../module/image.js');
http.createServer(function(request,response){//写文本// response.writeHead(200,{'Content-Type':'html/text;charset=utf-8'});//写图片response.writeHead(200,{'Content-Type':'image/jpeg'});if(request.url !== '/favicon.ico'){//清除第二次访问console.log('访问');imgFile.readImg('../imgs/vue.png',response);// response.end("");}
}).listen(8003);
console.log('Server running at http://127.0.0.1:8003/')
images.js
var fs=require('fs');module.exports={readImg:function(path,res){fs.readFile(path,'binary',function(err,file){if(err){console.log(err);return;}else{console.log('输出图片');res.write(file,'binary');res.end();}});},};