zoukankan      html  css  js  c++  java
  • Node以数据块的形式读取文件

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

      

  • 相关阅读:
    xgboost保险赔偿预测
    XGBoost对波士顿房价进行预测
    XGBoost 重要参数(调参使用)
    xgboost与gdbt的不同和优化
    基于OpenCV制作道路车辆计数应用程序
    卷积神经网络cnn的实现
    记一次bond引起的网络故障
    虚拟化讲座
    ubuntu16安装dhcp server
    frp内网穿透新玩法--结合xshell隧道
  • 原文地址:https://www.cnblogs.com/luxh/p/4130412.html
Copyright © 2011-2022 走看看