Must res.end() be called in express with node.js?

node.jsExpress

node.js Problem Overview


I have several Express applications, and I see that in some modules, res.end() is called at the end of a request handler (after res.send or res.json), while in others, it isn't called.

For example:

app.get('/test', function(req, res) {
    res.send('Test', 200);
});

or:

app.get('/test', function(req, res) {
    res.send('Test', 200);
    res.end();
});

Both cases work, but I'm afraid about leaks or running out file descriptors or something like that, when I run many requests. Which one is "more correct"?

node.js Solutions


Solution 1 - node.js

The answer to your question is no. You don't have to call res.end() if you call res.send(). res.send() calls res.end() for you.

Taken from /lib/response.js, here is the end of the res.send() function:

  //. . .
  // respond
  this.end(head ? null : body);
  return this;
}

Solution 2 - node.js

one example where you must call end() function is when you send buffer as a file to download.

res.write(buffer);
res.end();

Solution 3 - node.js

> res.end([data] [, encoding])

Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. Use to quickly end the response without any data.

> If you need to respond with data, instead use methods such as > res.send() and res.json().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongreuzeView Question on Stackoverflow
Solution 1 - node.jsJayView Answer on Stackoverflow
Solution 2 - node.jsKonstantin AdamovView Answer on Stackoverflow
Solution 3 - node.jsAdiiiView Answer on Stackoverflow