file - nodejs - fs.createReadStream().pipe,如何知道文件大小问题

标签 file http node.js httpresponse

我正在编写自己的 HTTP 模块,如果我需要使用二进制文件进行响应,例如.jpg,

我使用以下方法加载文件:body = fs.createReadStream(pathOfFile)

当我生成响应时,我使用:body.pipe(socket);

但是作为它的 HTTP 响应,我想添加一个 Content-Length header 。

我找不到一个简单的方法来做到这一点,fs.stat 不会立即给出结果,而是在我调用 pipe 之后。

无论如何要知道在 Content-Length header 中发送什么。 ?

谢谢。

最佳答案

好吧,你应该只在使用 fs.stat 获得大小后发送响应并通过管道传输文件,如下所示:

fs.stat(file_path, function(error, stat) {
  if (error) { throw error; }
  response.writeHead(200, {
    'Content-Type' : 'image/gif',
    'Content-Length' : stat.size
  });
  // do your piping here
}); 

关于file - nodejs - fs.createReadStream().pipe,如何知道文件大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8576121/

相关文章:

file - 如何检查给定路径是文件还是目录?

node.js - 尽管文件存在,为什么 `grunt watch` 失败并显示 "ENOENT, no such file or directory"

node.js - ES6 和 Node 中的同步和异步回调函数

javascript - Node.js,Express : Cannot set headers after they are sent to the client

c++ - 应用程序可以伪装成文件或文件夹吗?

c - 用C语言为文本文件构建Merkle树,每次重复该过程,都会生成一个新的根哈希

linux - 比较大文件

node.js - 收到第一个字节后停止 superagent(只获取重定向 url)

ajax - 什么会导致客户端不设置 cookie?

java - 每秒对 JSON 对象进行 HTTP 发布