首页 > Web开发 > 详细

nodeJS基础08:读取图片

时间:2017-01-04 07:31:49      阅读:342      评论:0      收藏:0      [点我收藏+]

1.读取图片

//server.js
var http = require("http");
var readImage = require("./readImage");
http.createServer(function(res, res){
    // res.writeHead(200, {"Content-Type":"text/html; charset=uf-8"});
    res.writeHead(200, {"Content-Type":"image/jpeg"});
    if (res.url!=="/favicon.ico") {
        //res.write(‘hello,world‘);//不能向客户端输出任何字节,否则会影响图片的输出
        readImage.readImage(‘./test.png‘, res); //如果文件路径存在则添加数据,如果不存在则新建文件并且添加数据
        console.log("继续执行");
        //res.end(‘end‘); 在 readImage.readImage方法中已经写过了
    }
}).listen(8000);
console.log(‘Server running at http://127.0.0.1:8000/‘);
// readImage.js
var  fs=  require(‘fs‘);
module.exports={
    readImage:function(path,res){
        fs.readFile(path,‘binary‘,function(err,  file)  {
            if  (err)  {
                console.log(err);
                return;
            }else{
                console.log("输出文件");
                res.writeHead(200,  {‘Content-Type‘:‘image/jpeg‘});
                res.write(file,‘binary‘);
                res.end();
            }
        });
    }
}; 

注意:在读取图片的过程不能向页面写入任何东西。

现在我们能够向浏览器输出文字,或者图片。下一节我们将学习如何向浏览器同时输出文字和图片。

 

nodeJS基础08:读取图片

原文:http://www.cnblogs.com/noper/p/6246993.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!