1、在node.js的www目录下新建n11.js、n12.js、a.html三个空文件,找一个png文件重命名为a.png放到www目录下。a.html内容随意写几个aaa;
2、n12.js内容为var fs = require('fs');//调用nodejs自带的fs对象module.exports={ r1:function(path,res){ //调用fs对象读指定路径的文件内容。 fs.readFile(path,'binary',function(err,filecon){ if(err){ console.log(err); }else{ res.write(filecon,'binary'); res.end(); } }); }}
3、n11.js内容为var http = require('http');//调用nodejs自带的http对象var f1 = require('./n12');//用http对象调用createServer方法来监听 本地8000端口//createServer方法中有两个内置参数对象,其中request为请求对象,response为响应体http.createServer(function(request,response){ //响应体写出头部信息response.writeHead(200,{'Content-Type':'image/jpeg'}); if(request.url!=='favicon.ico'){ f1.r1('./a.png',response); }}).listen(8000);//输出内容到控制台console.log('用http对象调用createServer方法来监听 本地8000端口');
4、命令行运行node n11.js来监听8000端口
5、浏览器地址栏输入localhost:8000回车,n11.js代码中所读取的a.png图片文件就显示在客户端浏览器中了。
6、本案例中读取图片的函数 , 是否也可以用于读取html文件并显示呢?也是可以的,只要把response.writeHead(200,{'Content-Type':'image/jpeg'});改为response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});f1.r1('./a.png',response);改为f1.r1('./a.html',response);