How to get the 'Content-Length' please?

How to get the content-length of a response please? response.headers.get('Content-Length') returns null.
See the example below, which is taken from this page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    // Step 1: start the fetch and obtain a reader
    const start = async function (a, b) {
        let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');


        const reader = response.body.getReader();

// Step 2: get total length
        const contentLength = +response.headers.get('Content-Length');

// Step 3: read the data
        let receivedLength = 0; // received that many bytes at the moment
        let chunks = []; // array of received binary chunks (comprises the body)
        while (true) {
            const {done, value} = await reader.read();

            if (done) {
                break;
            }

            chunks.push(value);
            receivedLength += value.length;

            console.log(`Received ${receivedLength} of ${contentLength}`)
        }

// Step 4: concatenate chunks into single Uint8Array
        let chunksAll = new Uint8Array(receivedLength); // (4.1)
        let position = 0;
        for (let chunk of chunks) {
            chunksAll.set(chunk, position); // (4.2)
            position += chunk.length;
        }

// Step 5: decode into a string
        let result = new TextDecoder("utf-8").decode(chunksAll);

// We're done!
        let commits = JSON.parse(result);
        alert(commits[0].author.login);
    }

    start()
</script>

</body>
</html>

The answer is right there on the page you linked:

It may be absent for cross-origin requests (see chapter Fetch: Cross-Origin Requests) and, well, technically a server doesn’t have to set it. But usually it’s at place.

And I’d question the claim that it’s “usually” there. For static data that’s true, but dynamically generated data will pretty often be sent without a Content-Length header, using chunked encoding.

So, how can one get the Content-Length then? Or this is not possible since the server doesnt send it?

You can’t get a header the server never sent. If you need the length of
the received data you can calculate that after receiving all of it. Note
however that some HTTP responses may not have an end, e.g. when
receiving an audio or video stream (depending on the format).

OK, many thanks for that! I wasnt quite sure to be honest. I looks like an important piece of info to be left out

2 Likes