node.js读取图片文件并显示

2025-10-21 11:37:39

1、在node.js的www目录下新建n11.js、n12.js、a.html三个空文诉海贪件,找一个png文件重命名为a.png放到www目录下。a.html内容随意写几个aaa;

node.js读取图片文件并显示

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();

}

});

}

node.js读取图片文件并显示

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端口');

node.js读取图片文件并显示

4、命令行运行node n11.js来监听8000端口

node.js读取图片文件并显示

5、浏览器地址栏输入localhost:8000回车,n11.js代码中所读取的a.png图片文件就裹码显示在客户端浏览器中了。

node.js读取图片文件并显示

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);

node.js读取图片文件并显示

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢