北在北方

太白枝头看,花开不计年,杯中浮日月,楼外是青天。

导航

Node以数据块的形式读取文件

Posted on 2014-11-29 11:04  CN.programmer.Luxh  阅读(622)  评论(0编辑  收藏  举报

  在Node中,http响应头信息中Transfer-Encoding默认是chunked。

Transfer-Encoding:chunked

  Node天生的异步机制,让响应可以逐步产生。

  这种发送数据块的方式在涉及到io操作的情况下非常高效。Node允许以数据块的形式往响应中写数据,也允许以数据块的形式读取文件。

  这样可以有高效的内存分配,不需要把文件全部读取到内存中再全部响应给客户,在处理大量请求时可以节省内存。

var http = require('http');
var fs = require('fs');


http.createServer(function(req,res){
    res.writeHead(200,{'Context-Type':'image/png'});

    var imagePath = 'D:/home.png';

    var stream = fs.createReadStream(imagePath);

    //一块一块的读取数据
    stream.on('data',function(chunk){
        res.write(chunk);
    });

    stream.on('end',function(){
        res.end();
    });

    stream.on('error',function(){
        res.end();
    });
}).listen(3000);

  Node还提供了一个更简洁的方法pipe()

var http = require('http');
var fs = require('fs');


http.createServer(function(req,res){
    res.writeHead(200,{'Context-Type':'image/png'});

    var imagePath = 'D:/home.png';

    var stream = fs.createReadStream(imagePath);
    stream.pipe(res);
    
}).listen(3000);