0

Suppose there's a file on the server: https://cdn.lr-in.com/LogRocket.min.js

How can I see the file size (preferably in KB) without downloading it?
Code snippet should be executable in chrome dev tools so no node.js code, please.

Unfortunately Is there a way to display the size of a file without downloading it? doesn't provide a reliable solution as there's no requirement that the Content-Length header is present in the headers of responses to HEAD requests.

From Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content (HEAD)

The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request had been a GET, except that the payload header fields (Section 3.3) MAY be omitted

The Content-Length header is one of these payload headers and there is no requirement to include it in HEAD responses (although, if it is included it must be correct.)

As you can see, the Content-Length header is not returned for this request!

fetch('https://cdn.lr-in.com/LogRocket.min.js', {method: 'HEAD'})
  .then((result) => {
    for (let key of result.headers.keys()){
      console.log(`Header: ${key}`);
    }
  });
phuzi
  • 12,078
  • 3
  • 26
  • 50
GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
  • https://stackoverflow.com/questions/56137006/is-there-a-way-to-display-the-size-of-a-file-without-downloading-it – Lee Taylor Jun 07 '22 at 14:13
  • Did a quick test and the that duplicate doesn't always work as there's no gurantee that the Content-Length header will be present although it _SHOULD_ be. – phuzi Jun 07 '22 at 14:26
  • Yeah, [docs](https://httpwg.org/specs/rfc7231.html#HEAD) say that the payload headers (incl. Content-Length) may be ommited for HEAD requests. Using HEAD request is not reliable. Don't know if you're going to find an answer to this though – phuzi Jun 07 '22 at 15:53
  • that's okay if there's no working solution for now but let's keep the question open so if someone ever knows a workaround they can help – GorvGoyl Jun 07 '22 at 16:25
  • 2
    I don't see how it can ever be possible without the header because only the server can know the size (sometimes even the server doesn't know it, by the way) and so if it doesn't tell you, there can't be any way for you to find out. – CherryDT Jun 08 '22 at 08:03
  • "I don't see how it can ever be possible" that's a very strong statement. Anyway, how do browsers know the file size when they just initiate downloading a file? is there a way in js to initiate a download to get the file size and then cancel the download process. – GorvGoyl Jun 08 '22 at 11:26
  • 1
    A browser knows because they get the size from the header of the request they use to download the file (assuming `Content-Length` is even set, because a browser won't know either if `Transfer-Encoding: chunked` is used). – Mark Rotteveel Jun 10 '22 at 08:47

0 Answers0