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

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

Transfer-Encoding:chunked

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

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

[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:1f15eba6-fafa-4577-898b-4ed76820e990

[En]

[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:11492ae6-c20f-472e-b36b-dbb85ddd8ed2

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

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

Original: https://www.cnblogs.com/luxh/p/4130412.html
Author: CN.programmer.Luxh
Title: Node以数据块的形式读取文件

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/562551/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球