-1

I'm using Node.js for backend (I'm just testing it with localhost), and I noticed that with this code...

response.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', (_err, data) => {
    response.end(data);
});


response.writeHead(200, {'Content-Type': 'application/json'})
const responseBody = { headers, method, url, body };
response.write(JSON.stringify(responseBody));
response.end();

...the second response.end() call was "overwriting" the first one (the html page was never shown).


So I decided to use setTimeout to see if I could make appear the content of index.html first, and then after a few seconds the application/json response...

setTimeout(() => {
    response.writeHead(200, {'Content-Type': 'application/json'})
    const responseBody = { headers, method, url, body };
    response.write(JSON.stringify(responseBody));
    response.end();
}, 1000);

...but after the first response.end() call I could never see the json appear.


Then I had a strange idea, I decided to change the timeout from 1000ms to 1ms, and the html content was never shown, I immediately (or maybe after 1ms, which is such a small amount of time) saw the json content.

I tried with 10ms but it worked as with 1000ms, then I tried with 2ms, and refreshing the page it sometimes showed json and sometimes html.


How is this possible? The response.end() function doesn't wait until the response has ended? Is it caused by something else? Thank you in advance.

7
  • 1
    It's not clear what you are trying to achieve here. You cannot write two different responses on the same connection.
    – Bergi
    Apr 4, 2022 at 14:47
  • 1
    "How is this possible? The response.end() function doesn't wait until the response has ended?" - No (or maybe, but irrelevant). What doesn't wait in your code is the asynchronous fs.readFile(…) call.
    – Bergi
    Apr 4, 2022 at 14:48
  • @Bergi, I know, it was just a try and I was surprised by the fact that one response.end() was overwriting the other one.
    – FLAK-ZOSO
    Apr 4, 2022 at 14:49
  • 2
    It's more like "preventing the other one from having any effect". Because after one calls end, whatever the other one tried to send, it won't be sent.
    – qrsngky
    Apr 4, 2022 at 14:51
  • 2
    @qrsngky I really wonder why that doesn't throw an exception, like "response is already written" or "stream is already closed".
    – Bergi
    Apr 4, 2022 at 15:23

2 Answers 2

3

I think you're correct in saying that response.end() does not wait until file transfer is actually ended.

I actually learned that while using express: If you do response.sendFile(...) followed by response.end() in the same function, then no actual file is sent (the response is 'closed' before the file can actually be sent), it just gives an empty response.


Edit:

In your first code, the JSON writing is always executed earlier than the readFile callback. (The readFile callback is having an asynchronous behavior.)


But once you have the timeout, there is a race between the "timeout callback" and "readFile callback".

Since file loading times can vary, it may be sometimes faster than the timeout and sometimes slower. But whichever callback 'wins the race', it will call the response.end(), preventing the other one from sending anything.

6
  • So response's methods have an asynchronous behaviour?
    – FLAK-ZOSO
    Apr 4, 2022 at 14:39
  • Yes, I think it's designed that way. Otherwise, the server would have to stop doing anything other than loading the entire file. From the user's perspective, it's almost like the server 'hangs'.
    – qrsngky
    Apr 4, 2022 at 14:41
  • Ok, thanks, but the problem here isn't due to a response ending too early, but to a response not really ending, since there's an other response.end() call after a few lines and it really ends the response.
    – FLAK-ZOSO
    Apr 4, 2022 at 14:43
  • 3
    @FLAK-ZOSO In your first code, the JSON writing is always executed earlier than the readFile callback. (The readFile callback is having an asynchronous behavior.) But once you have the timeout, there is a race between the "timeout callback" and "readFile callback". Since file loading times can vary, it may be sometimes faster than the timeout and sometimes slower. But whichever callback 'wins the race', it will call the response.end, preventing the other one from sending anything.
    – qrsngky
    Apr 4, 2022 at 14:49
  • This is exactly the answer I was searching for, if you could write it in your answer I'll accept it, thank you 🙂
    – FLAK-ZOSO
    Apr 4, 2022 at 14:52
1

When you use setTimeout, the code you're timing out, is pushed to the "end" of the execution stack, and normal program execution resumes.

In this case sending the response and everything that would happen if you'd straight out delete the code there.

2
  • Yes, but why do different things happen when timeout is changed from 1ms to 2ms?
    – FLAK-ZOSO
    Apr 4, 2022 at 14:32
  • 1
    1ms is an eterntity in cpu time. A lot of things happen in that time. Imagine if only one instruction would happen in one nano second, then in one millisecond, 1 000 000 instructions will have occurred. In 2 milliseconds 2 000 000 before your script kicks in. There is a lot that can happen in that time for code.(for comparison, that would mean a cpu running at 1 Mhz or something near there... Last released the RISC-I in 1982 ran that fast at max speed, in reality your script will run many more instructions on your Ghz beast) Apr 4, 2022 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.