Node.js缓冲区长度

时间:2014-11-19 22:05:24

标签: node.js express

如何在HTTP响应中为缓冲区设置正确的长度?

我正在使用Express.js。我无法让这个工作:

res.set('Content-Length', myBuffer.length);

注意,我需要手动设置它,因为我需要在HEAD请求中发送它。如果我只发送HEAD响应而不手动设置GET请求体大小的Content-Length,那么Content-Length设置为2比14000的小值。

2 个答案:

答案 0 :(得分:0)

你的代码应该可以完成这项工作,但是你没有给我们任何关于如何获得你的myBuffer的线索。

以下是一个有效的代码示例,前提是有一个文本文件h:\ Temp \ text.txt

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

http.createServer(function (request, response) {
    fs.readFile('H:\\Temp\text.txt', function(data, err) {
        if (err) {
            response.writeHead(404, {
                "Content-Type": "text/plain"
            });
            response.write(err);
            response.end();
        } else {
            response.writeHead(200, {
                "Content-Type": "text/plain"
                "Content-Length": data.length
            }
            response.write(data);
            response.end();
        }
    });
}).listen(80);

它起作用,因为数据是一个正确的Buffer对象。 如果数据不是Buffer对象,而只是一个字符串或其他任何东西,它就无法工作。 (例如,UTF-8字符串的字符数可以少于字节数)。

答案 1 :(得分:0)

尝试“buffer.body.length

@Post("posts/add")
async addPost(
    @Body() body
  ) {
    ...

  res.set({
    'Content-Length': buffer.body.length,
  });
    
    ...
}
相关问题